Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

React에서 CORS 이슈 해결하기 #4

Open
yunyoung1819 opened this issue Jun 26, 2023 · 0 comments
Open

React에서 CORS 이슈 해결하기 #4

yunyoung1819 opened this issue Jun 26, 2023 · 0 comments
Assignees
Labels
bug Something isn't working React

Comments

@yunyoung1819
Copy link
Owner

yunyoung1819 commented Jun 26, 2023

상황

  • 토이 프로젝트에서 admin 서버 개발 중 admin 클라이언트(localhost:3000)에서 admin 서버(localhost:8080)로 API 요청을 보낼 때 CORS가 발생함
  • CRA(create-react-app) 클라이언트에서 프록시 설정을 통해 해결하는 방법을 기술

원인

  • CORS (Cross Origin Resource Sharing)의 약자로 현재 애플리케이션의 도메인에서 다른 웹페이지 도메인으로 리소스가 요청되는 경우를 나타냄
  • 예를 들어 'https://apis.data.go.kr/' 에서 'http://localhost:3000' 도메인으로 API 요청을 하게 되면 http 형태로 요청이 되므로 브라우저 자체에서 보안 상 이유로 CORS를 제한

해결

  1. package.json에서 proxy를 설정하는 첫번째 방법
  • package.json
{
    "proxy": "https://apis.data.go.kr/"
}

이렇게 설정을 해주게 되면 API 서버와 동일한 도메인이 됨으로서 CORS 정책 해결 및 Access-Control-Allow-Origin의 허용을 받을 수 있음

  1. http-proxy-middleware를 통한 두번째 방법
  • npm install
npm install http-proxy-middleware --save
  • ser/setupProxy.js 파일 생성
const { createProxyMiddleware } = require('http-proxy-middleware');

module.exports = function(app) {
    app.use(
        '/api',
        createProxyMiddleware({
            target: 'http://localhost:8080',
            changeOrigin: true,
        })
    );
};
  • Rest API 호출 부분
import React, { useEffect } from 'react';
import axios from 'axios';

function LandingPage() {
    useEffect(() => {
        axios.get('api/hello')
        .then(response => console.log(response.data))
    }, [])
    return (
          <div>
             LandingPage
          </div>
    )
}

export default LandingPage;

참고

@yunyoung1819 yunyoung1819 added bug Something isn't working React labels Jun 26, 2023
@yunyoung1819 yunyoung1819 self-assigned this Jun 26, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working React
Projects
None yet
Development

No branches or pull requests

1 participant