관리 메뉴

웹개발자의 기지개

[Vue.js] CORS 에러 문제 해결하기 - proxy 설정하기 본문

javascript/Vue.js

[Vue.js] CORS 에러 문제 해결하기 - proxy 설정하기

http://portfolio.wonpaper.net 2023. 10. 6. 19:15

CORS(Cross-Origin Resource Sharing)

 

Access to XMLHttpRequest at 'http://localhost:8989/api' from origin 
'http://localhost:8080' has been blocked by CORS policy: 
No 'Access-Control-Allow-Origin' header is present on the requested resource.

 

브라우저 자체 보안 관련 사항으로 cross-origin HTTP 요청에 대하여 서버 동의가 필요하고, 이에 동의되지 않을때 거절되는 보안 매커니즘이다.

 

보통의 경우 Backend 와 Frontend 사이의 HTTP 관련 개발환경이 달라서 이를 proxy 설정을 해놓음으로써 자연스레 보안문제 해결을 할수가 있다.

 

여기서는 FrontEnd 상에서 Proxy 설정을 잡는 방법을 알아본다.

 

 

[ proxy 설정하기 ]

 

[ vue.config.js ]

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
  transpileDependencies: true,
  // 단일 단어 컴포넌트 사용가능하도록
  lintOnSave:false,
  devServer: {
    proxy: {
      '/api': {
        target: 'https://api서버도메인주소',
        changeOrigin: true,
        pathRewrite : {
          '^/api' : ''
        }
      },
      '/filedownload' : {
        target: 'https://filedownload',
        changeOrigin: true,
        pathRewrite : {
          '^/filedownload' : ''
        }        
      }
    }
  } 
})
 
cs

devServer 안에 proxy 설정을 한다. 

 

axios.get("/api/GetNoticeView");  형태로 Vue 파일 상에서  코딩하면,

proxy 설정소스를 거쳐서 https://api서버도메인주소/GetNoticeView  형태로 자동 타켓팅해준다.

 

 

참고 :  https://velog.io/@minsu2344/Vue-CORS-%EC%97%90%EB%9F%AC-vue.config.js%EB%A1%9C-%ED%95%B4%EA%B2%B0

참고 : https://eunjinii.tistory.com/47

 

 

 

 

 

 

 

 

Comments