카테고리 없음

CORS Issue: Next.js / React application

mark340 2024. 3. 7. 14:05

React

  // webpack
  devServer: {
  
    ...
    
    proxy: {
      "/api": {
        target: "https://api.sampleapis.com/futurama",
        pathRewrite: {"/api": "/"}, 
      }
    }
  },

먼저 웹팩에서 proxy 부분을 추가해준다. 설정은 이렇다.
/api로 시작하는 경로는 실제로 https://api.sampleapis.com/futurama의 경로라는 것이다. 그리고 pathRewrite를 이용하여 /api를 /로 바꿔준다.

 

const res = await axios.get('https://api.sampleapis.com/futurama/info');

const res = await axios.get('/api/info');

이제 위의 방법으로 요청하던 코드를 아래로 변경할 수 있다.

 

 

Next.js

Next.js 공식 문서

하지만 나는 Next.js를 사용하고 있었으므로 위의 방법으로 해결하지는 않았다.

 

//next.config.js
/** @type {import('next').NextConfig} */
const nextConfig = {
  reactStrictMode: true,
  async rewrites() {
    return [
      {
        source: '/api/:path*',
        destination: `API주소/:path*`,
      },
    ];
  },
};

module.exports = nextConfig;

먼저 React에서 webpack-dev-server에서 해준것 처럼 비슷하게 설정을 해주면 된다.

 

    try {
      const res = await axios({
        method: 'patch' as Method,
        url: `/api/coupon/${code}`,
        data: { status: 'USED', selection: checkedItems },
      });
      setQrData(prev => ({
        ...prev,
        status: 'USED',
      }));
      console.log(res);
    } catch (err) {
      console.log(err);
    }

그리고 /api/coupon/${code} 와 같이 사용해주면된다.
(위의 코드에서는 그냥 url부분만 어떻게 쓰는지 보고 넘어가면 된다.)