Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

내가 CORS 이슈를 해결한 방법 - Proxy #54

Open
NewWisdom opened this issue Jun 16, 2021 · 0 comments
Open

내가 CORS 이슈를 해결한 방법 - Proxy #54

NewWisdom opened this issue Jun 16, 2021 · 0 comments
Labels
atdd-subway-path 지하철 경로조회 / 로그인 SpringBoot 스프링

Comments

@NewWisdom
Copy link
Owner

  • CORS 이슈를 해결하기 위해서 서버쪽, 프론트쪽에서 해결하는 방법이 있음
  • 나는 미션에서 CORS 이슈를 마주치지 못했는데, 왜그러나 했더니 내가 프론트쪽에서 CORS가 발생하지 않게 처리한 것이였음

서버에서 해결

  • HTTP 응답에서 Access-Control-Allow-Origin: 허용하고자 하는 도메인 설정
@Configuration
public class WebConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedMethods("*")
                .allowedOriginPatterns("*")
                .allowCredentials(true);
    }
}
  • 또 인터셉터에서 예비 요청이 OPTION에 대해서는 토큰을 검증하지 않도록 해당 메서드일 시 preHandle()을 안타도록 설정
if (request.getMethod().equals("OPTIONS") 
    return false;
}

프론트쪽 해결 - Proxy 서버를 이용

프록시 서버: 클라이언트가 자신을 통해서 다른 네트워크 서비스에 간접적으로 접속할 수 있게 해 주는 컴퓨터 시스템이나 응용 프로그램을 가리킨다. 서버와 클라이언트 사이에 중계기로서 대리로 통신을 수행하는 것을 가리켜 '프록시', 그 중계 기능을 하는 것을 프록시 서버라고 부른다.

  • 리소스 요청하는 서버 사이에 프록시 서버를 하나 거쳐서 요청,응답을 주고 받음
  • 백 서버는 8000번 포트이고 프론트 서버는 8081번 포트인 경우, 프론트(8081)에서 온 요청을 마치 백(8080)에서 온것처럼 바꿔주는게 프록시의 역할
  • 같은 도메인 , 포트번호를 사용하는 것처럼 보이게 만듦

현재 프론트엔드에서 vue cli를 사용하고 있어 프론트 서버를 구동시킬 때 다음 명령어를 친다.

npm run serve

이러면 webpack-dev-server 기반의 dev 서버를 실행시킨다.
여기서 프록시를 설정하면 브라우저가 준 요청에 대해 dev 서버가 그 요청을 가로채 서버에 요청을 하고 응답을 받게 된다.
그러면 웹 애플리케이션이 요청을 보낸것이 아니기 때문에 CORS에 걸리지 않는다.

image

vue.config.js

const path = require('path');
module.exports = {
    outputDir: path.resolve(__dirname, '../src/main/resources/static/'),
    devServer: {
        proxy: {
            '/': {
                target: 'http://localhost:8080',
                ws: true,
                changeOrigin: true,
            },
        },
    },
};
  • target: server의 주소
  • changeOrigin: Cors에러를 막기위한 옵션

참고 자료

@NewWisdom NewWisdom added SpringBoot 스프링 atdd-subway-path 지하철 경로조회 / 로그인 labels Jun 16, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
atdd-subway-path 지하철 경로조회 / 로그인 SpringBoot 스프링
Projects
Development

No branches or pull requests

1 participant