mark340
착하게살자
mark340
전체 방문자
오늘
어제
  • 분류 전체보기 (98)
    • 백준 (11)
    • 알고리즘 (1)
    • Javascript (17)
    • CS (18)
    • 기타 (9)
    • AI (1)
    • Angular (2)
    • Linux (14)

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

인기 글

태그

  • JavaScript
  • parsing
  • oauth
  • Closure
  • MySQL

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
mark340

착하게살자

카테고리 없음

CORS Issue: Next.js / React application

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부분만 어떻게 쓰는지 보고 넘어가면 된다.)

저작자표시 (새창열림)
    mark340
    mark340
    착하게삽시다

    티스토리툴바