여러 proxy 설정 위한 CORS 에러 해결

realzu·2022년 8월 27일

has been blocked by CORS policy

기존에 백엔드 서버를 연결하기 위해 package.json에 proxy를 설정했는데, 오픈 API url을 추가하게 되면서 또다시 CORS를 만나게 되었다. 추가된 url을 어떻게 처리해야 하나 알아보았다.

📍 http-proxy-middleware

package.json 외에 CRA 공식 홈페이지에도 나와 있는 http-proxy-middleware가 있다. 여러 경로의 proxy 설정을 커스터마이징 할 수 있다.

$npm install http-proxy-middleware

setupProxy

src 폴더 하위에 setupProxy 파일을 생성할 것이다. 타입스크립트의 경우, 타입스크립트의 CRA는 http-proxy-middleware를 지원하지 않는다고 한다. 따라서 js파일로 생성하면 자동으로 세팅된다.

//setupProxy.js
const { createProxyMiddleware } = require('http-proxy-middleware');

module.exports = function(app) {
    app.use(
    createProxyMiddleware('/api', {
        target: 'https://api.openweathermap.org/data/2.5/group',
        pathRewrite: { '^/api': '' },
        changeOrigin: true,
        })
    );
};

/api 는 프로젝트에서 사용할 사용자 지정 주소명이다.
target은 실행 시 proxy에 의해 해당 url로 요청된다.
pathRewrite는 '/api'가 공백으로 대체된다는 것이다.
changeOrigin은 호스트 헤더의 변경을 하는 옵션이다.

axios url

이제 axios를 통해 데이터를 요청할 때 url을 방금 위에서 설정한 /api 내용으로 대체하면 된다!

cf)
https://github.com/chimurai/http-proxy-middleware
https://velog.io/@hotbreakb/cors-error
https://egas.tistory.com/39
https://keravi.tistory.com/19

profile
부딪히지 않으면 아무 일도 일어나지 않는다 👊

0개의 댓글