programing

React(이형 앱)에서 API 호출 시 'Access-Control-Allow-Origin' 문제 발생

showcode 2023. 3. 21. 22:44
반응형

React(이형 앱)에서 API 호출 시 'Access-Control-Allow-Origin' 문제 발생

리액트와 익스프레스를 사용하는 동형 자바스크립트 앱에 문제가 생겼습니다.

내 컴포넌트가 마운트되면 actios.get을 사용하여 HTTP 요청을 하려고 합니다.

componentDidMount() {
  const url = 'http://ufc-data-api.ufc.com/api/v3/iphone/fighters/title_holders';
  axios.get(url).then( res => {
    //use res to update current state
  })
}

API에서 상태 200 res가 표시되지만 응답 데이터가 표시되지 않고 콘솔에 오류가 표시됩니다.

XMLHttpRequest cannot load http://ufc-data-api.ufc.com/api/v3/iphone/fighters/title_holders. 
No 'Access-Control-Allow-Origin' header is present on the requested resource. 
Origin 'http://localhost:3000' is therefore not allowed access.

단, 내 서버에서 요청을 했을 경우.js

const url = 'http://ufc-data-api.ufc.com/api/v3/iphone/fighters/title_holders';
axios.get(url).then(res => {
    //console.log(res);
});

정상적으로 동작해, 서버가 기동하면 응답 데이터가 표시됩니다.이게 실제 API의 문제인가요?아니면 제가 잘못하고 있는 건가요?만약 이것이 CORS의 문제라면 server.js의 요청도 효과가 없을 것이라고 생각합니다.감사합니다!

CORS는 브라우저 기능입니다.브라우저가 같은 발신기지 정책을 우회할 수 있도록 서버는 CORS에 가입해야 합니다.서버에는 동일한 제한이 없으며 공용 API를 사용하여 서버에 요청을 할 수 있습니다.https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS

웹 앱의 프록시 역할을 할 수 있는 CORS를 사용하도록 설정한 서버에 끝점을 만듭니다.

외부 프록시 또는 Chrome 확장을 사용하지 않고 수정

를 하게 할 CORS 를하게 할 수 를 들면, 외부 API 를 해), 「CORS」를 합니다.서버상에서 CORS를 유효하게 할 수 없는 경우(외부 API를 사용하는 경우 등), 미들웨어를 만듭니다.React -> Middleware -> Orginal Server.

  1. 하여 Node.js의 아래 합니다.app.js.

    const express = require("express");
    var cors = require('cors')
    const app = express();
    app.use(cors());
    const { createProxyMiddleware } = require('http-proxy-middleware');
    app.use('/api', createProxyMiddleware({ 
        target: 'http://localhost:8080/', //original url
        changeOrigin: true, 
        //secure: false,
        onProxyRes: function (proxyRes, req, res) {
           proxyRes.headers['Access-Control-Allow-Origin'] = '*';
        }
    }));
    app.listen(5000);
    

은 요청 사항을 시킵니다.http://localhost:5000/api/xxx: (예:http://localhost:8080/api/xxx이치노

  1. 클라이언트(React)를 콜 프록시로 변경하여 CORS 오류 없이 데이터를 가져옵니다(url 포트만 변경하면 됩니다).

    axios.get('http://localhost:5000/api/xxx', //proxy uri
    {
       headers: {
          authorization: ' xxxxxxxxxx' ,
          'Content-Type': 'application/json'
       } 
    }).then(function (response) {
       console.log(response);
    });
    
  2. project " " " " 。node app.js리액션 프로젝트npm start.

[ Allow - Control - Allow - Origin ]라고 하는 Google Chrome Extension 을 사용합니다.* 이 기능은 응용 프로그램의 CORS 헤더를 즉시 수정합니다.

저도 같은 문제가 있었어요.다른 답은 맞지만 다른 해결책이 있습니다.응답 헤더를 설정하여 크로스 컨버전스 액세스를 허용할 수 있습니다. 게시물에 따르면 app.get 호출 전에 다음 코드를 추가해야 합니다.

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "X-Requested-With");
  next();
  });

이것은 나에게 효과가 있었다:)

        //install cors using terminal/command  
        $ npm install cors

        //If your using express in your node server just add
        var cors = require('cors');
        app.use(cors())


       //and re-run the server, your problem is rectified][1]][1]
       **If you won't be understood then see below image**

https://i.stack.imgur.com/Qeqmc.png

오늘 같은 오류에 직면했습니다.Respect with Typescript와 백엔드를 사용하여 Java Spring 부트를 사용하여 백엔드를 조작하고 있다면 CORS 컨피규레이션파일을 추가하는 것만으로 충분합니다.

다음 예에서는 allowed origin을 *로 설정하여 모든 것을 허용하지만 보다 구체적이고 http://localhost:3000과 같은 URL만 설정할 수 있습니다.

import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

@Configuration
public class AppCorsConfiguration {
    @Bean
    public FilterRegistrationBean corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        config.addAllowedOrigin("*");
        config.addAllowedHeader("*");
        config.addAllowedMethod("*");
        source.registerCorsConfiguration("/**", config);
        FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
        bean.setOrder(0);
        return bean;
    }
}

도 같은 를 겪고 있었다.fetch명령어를 입력합니다.여기서의 문서를 간단하게 보면, 이하를 알 수 있습니다.

요구하는 서버가 CORS를 지원하지 않는 경우 콘솔에 CORS Access-Control-Allow-Origin 헤더가 없기 때문에 크로스 오리진 요구가 차단되었음을 나타내는 오류가 나타납니다.

no-cors 모드를 사용하여 불투명한 리소스를 요청할 수 있습니다.

fetch('https://bar.com/data.json', {
  mode: 'no-cors' // 'cors' by default
})
.then(function(response) {
  // Do something with response
});

디버깅 모드에서 vs 코드를 사용할 때 이 코드를 사용할 수 있습니다.

"runtimeArgs" : ["--disable-web-security", --user-data-dir=~/ChromeUserData/"

launch.json

{
  "version": "0.2.0",
  "configurations": [
    {
      "type": "chrome",
      "request": "launch",
      "name": "Chrome disable-web-security",
      "url": "http://localhost:3000",
      "webRoot": "${workspaceFolder}",
      "runtimeArgs": [
        "--disable-web-security",
        "--user-data-dir=~/ChromeUserData/"
      ]
    }
  ]
}

또는 직접 실행

Chrome --disable-web-security --user-data-dir=~/ChromeUserData/

Create-React-App에는 이 문제를 해결하는 간단한 방법이 있습니다.즉, 패키지에 프록시 필드를 추가합니다.아래와 같은 json 파일

"proxy": "http://localhost:8081",

당신의 질문에 대한 답은 여기에 있다고 생각합니다.

Chrome에서 Access-Control-Allow-Origin을 헤더로 전송하려면 /etc/hosts 파일의 localhost에 다음과 같은 에일리어스를 붙이면 됩니다.

127.0.0.1 로컬호스트 yourdomain.com

서버에 CORS 헤더가 없기 때문에 응답을 받을 수 없습니다.

이것은 Chrome Browser에서 캡처한 API 헤더입니다.

Age:28
Cache-Control:max-age=3600, public
Connection:keep-alive
Date:Fri, 06 Jan 2017 02:05:33 GMT
ETag:"18303ae5d3714f8f1fbcb2c8e6499190"
Server:Cowboy
Status:200 OK
Via:1.1 vegur, 1.1 e01a35c1b8f382e5c0a399f1741255fd.cloudfront.net (CloudFront)
X-Amz-Cf-Id:GH6w6y_P5ht7AqAD3SnlK39EJ0PpnignqSI3o5Fsbi9PKHEFNMA0yw==
X-Cache:Hit from cloudfront
X-Content-Type-Options:nosniff
X-Frame-Options:SAMEORIGIN
X-Request-Id:b971e55f-b43d-43ce-8d4f-aa9d39830629
X-Runtime:0.014042
X-Ua-Compatible:chrome=1
X-Xss-Protection:1; mode=block

응답 헤더에 CORS 헤더가 없습니다.

이것이 도움이 될지는 모르겠지만 리액트 네이티브 어플리케이션을 리모트로 디버깅할 때 같은 에러가 발생하였습니다.192.168.x.x:8081에서 디버거를 실행하고 있었습니다.CORS(Cross-Origin Resource Sharing)에 대해 조금 읽고 CORS(초보자)가 무엇인지 알게 되었습니다.또, URL을 IP:8081에서 localhost:8081로 변경해, 문제가 해결되었습니다.

제 경우 서버 측에서 활성화해도 CORS 오류가 발생하였습니다.url 이이 。 localhost:4001/todos나는 'http' 앞에 붙이는 것을 잊었다.

http://localhost:4001/todos //correct way

고객 측에서 처리할 필요는 없습니다.다음 단계만 수행하면 됩니다.

순서 1:

npm install cors

순서 2:

//express-server.js  

...
const cors = require('cors');
app.use(cors());

알았어!

이는 리액트 앱이 localhost:3000에서 실행 중이고 apis가 다른 서버에 있기 때문에 리액트 앱을 통해 엔드포인트를 호출하려고 할 때 흔히 발생하는 문제입니다.

이 오류를 수정하려면 'syslog-middleware'를 설치합니다.

npm i http-proxy-middleware 
or
yarn add http-proxy-middleware

설치 후 setupProxy.jssrc 폴더에 만듭니다.

아래 코드를 따릅니다.

    const { createProxyMiddleware } = require('http-proxy-middleware');
    
    module.exports = function(app) {
    
        app.use(
        '/getDetails', //this is your api
        createProxyMiddleware({
          target:'http://10.0.0.20:9000/getDetails', //this is your whole endpoint link
          changeOrigin: true,
        })
      );


    app.use(
        '/getproducts', //this is your api
        createProxyMiddleware({
          target:'http://10.0.0.20:9000/getproducts', //this is your whole endpoint link
          changeOrigin: true,
        })
      );
      
    };

app.use에서 원하는 수만큼 api를 추가하고 정상적으로 api를 호출할 수 있습니다.

axios.get('http://10.0.0.20:9680/getDetails')

자세한 내용은 React JS의 개발에서 아래 링크 Porxying API 요청을 확인하십시오.

패키지에 프록시를 추가합니다.json 파일을 작성하고 url의 나머지 부분을 fetch 자체에 저장합니다.

예:

포장되어 있습니다.json 파일, "http:/https://www.google.com", //자신의 웹사이트 링크 추가

App.js 파일 const 응답 = wait fetch fetch fronthr/...(자신의 명령에 따라)

package.json의 개인 자산 뒤에 아래를 사용합니다.

"proxy": "http://localhost:5000", 

열쇠는proxy값은 서버 URL 입니다.

또한 Chrome은 로컬 호스트를 지원하지 않습니다.Access-Control-Allow-Origin 크롬 이세 코르스

또는

익스프레스를 이용하시는 경우, cors 사용 후 경로를 추가해 주십시오.

app.use(cors());  
app.use('/posts', postRoutes);

이것을 에 추가합니다.server.jsexpress 앱에서

const cors=require("cors");
 const corsOptions ={
       origin:'*', 
       credentials:true, //access-control-allow-credentials:true
        optionSuccessStatus:200,
 }

 app.use(cors(corsOptions)) 

꼭 뛰어가다npm install cors

서버 폴더에 「cors」를 인스톨 하는 것만으로, 같은 문제를 해결했습니다.express를 사용하여 api를 만들고 get request를 api로 전송하려고 했지만 "cors"가 없으면 동작하지 않았습니다.

언급URL : https://stackoverflow.com/questions/41497674/access-control-allow-origin-issue-when-api-call-made-from-react-isomorphic-ap

반응형