Project

EC2 서버에 올라간 Spring Boot와 React 연동 시 CORS 설정

yerinpark 2023. 7. 13. 17:46

CodeStates Project team 3 Backend 에러 및 해결

에러

EC2 서버에 올라간 Spring Boot와 React 연동 시 CORS 설정

 

 

해결

  1. React에서 package.json에
  2. 프록시 설정
    1. npm i http-proxy-middleware 로 라이브러리 설치
    2. setProxy.js 에 코드 추가
"proxy": "[<http://[주소]:[포트번호]>]",
const { createProxyMiddleware } = require("http-proxy-middleware");

module.exports = function (app) {
  app.use(
    createProxyMiddleware("/api/v1", {
      target: "http://localhost:8082",
      changeOrigin: true,
    })
  );
};

3. Spring Boot에서 WebMvcConfig 작성

package com.example.knu_vcs.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
    private final long MAX_AGE_SECS = 3600;

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("http://localhost:3000")
                .allowedMethods("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS")
                .allowedHeaders("*")
                .allowCredentials(true)
                .maxAge(MAX_AGE_SECS);
    }
}

 

참고

https://velog.io/@pjj186/리액트-스프링부트-연동-CORS-이슈-해결