반응형

localhost:3000 이라는 포트로 만들어진 react 프로젝트에서

다른 포트번호로 실행된 백단 프로젝트를 연결할때 api cors error 를 필연적으로 만나게된다.

 

해결방법은 간단하다

 

1. next.config.js 수정

/** @type {import('next').NextConfig} */
const nextConfig = {
  reactStrictMode: false, //true 면 next dev 실행할때 useEffect 2번씩 실행
  swcMinify: true,
  eslint: {
    ignoreDuringBuilds: true,
  },
  compiler: {
    styledComponents: true,
  },
  images: {
    unoptimized: true,
    domains: ['picsum.photos', 'img.dmitory.com', 'image.edaily.co.kr'],
  },
  webpack(config) {
    config.module.rules.push({
      test: /\.svg$/,
      use: ['@svgr/webpack'],
    })
    return config
  },
  //api cors 에러 프록시 설정
  async rewrites() {
    return [
      {
        source: '/api-aaa/:path*',
        destination: 'http://localhost:8080/api-aaa/:path*',
      },
      {
        source: '/api-bbb/:path*',
        destination: 'http://localhost:8090/api-bbb/:path*',
      },
      {
        source: '/api-ccc/:path*',
        destination: 'http://localhost:8443/api-ccc/:path*',
      },
      {
        source: '/upload/:path*',
        destination: 'http://localhost:8443/upload/:path*',
      },
    ]
  },
}

module.exports = nextConfig

 

 

rewrites 안쪽에 내가 통신하려고 하는 서버의 포트번호를 넣어주면 된다

나의 경우 멀티모듈을 사용했기때문에 저렇게 많은 포트가 필요했다

 

source 설정

지난 포스팅에 있는것처럼 api 호출할때 아래와 같은식으로 호출되는 부분이 있다고 한다면, 

getMenu = async ()=> {
    return await client.get('/api-aaa/menu/list')
}

 

/api-aaa/ 를 prefix로 삼고 api-aaa 로 통신하는 모든 uri들은 포트 8080으로 가게끔 경로를 틀어준다는 의미이다

 

destination 설정

만약 로컬에서 프론트/백단 소스를 모두 띄운다면 위 코드는 문제가 없겠지만

 

로컬에서 프론트 실행하고, 다른 서버에서 백단을  실행하거나

프론트/백단 소스코드를 모두 다른 서버(aws, linux 등..) 에서 실행한다면 destination 을 변경해야한다

...

async rewrites() {
    return [
      {
        source: '/api-aaa/:path*',
        destination: 'http://서버IP:8080/api-aaa/:path*',
      },
      {
        source: '/api-bbb/:path*',
        destination: 'http://서버IP:8090/api-bbb/:path*',
      },
      {
        source: '/api-ccc/:path*',
        destination: 'http://서버IP:8443/api-ccc/:path*',
      },
      {
        source: '/upload/:path*',
        destination: 'http://서버IP:8443/upload/:path*',
      },
    ]
  },

...

 

localhost 부분을 서버IP로 바꿔주면 된다.

 

 

2. 백단 소스코드수정

만약 WebConfig 를 설정하는 소스코드가 있다면 해당부분을 수정하고 없다면 새로만들어주자

@Configuration 으로 전체검색했을때 없으면 없는것

 

@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Value("${config.server-url}")
    String serverUrl;

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("http://" + serverUrl + ":3000") // 프론트의 주소와 포트번호
                .allowedMethods("GET", "POST")
                .allowCredentials(true);
    }

}

 

 

나는 get 과 post만 열어줬고 이 설정만 추가하면 잘될것!!

 

혹시 allowedOrigins에 다른 ip주소도 추가해야한다면 아래와같이 콤마로 추가할수있다

.allowedOrigins("http://" + serverUrl + ":3000", "http://어쩌고ip:3000")

 

 

그래도 안된다면, spring security 사용하고있는경우 security 설정에서 막고있는게 아닌지 확인해야 한다.

 

그래도 안된다면!! IP주소 혹은 API PATH 오타가 있지는 않은지 확인해보자

728x90

+ Recent posts