VueJS

[VueJS] CORS(Cross-Origin Resource Sharing) 처리

봉주니 2024. 2. 18. 02:04

1. 프론트엔드에서 처리

프론트에서 백엔드 서비스를 부를 때, 호출하는 Origin(url) 이 달라서 발생하는 충돌이다.

아래와 같이 proxy 처리를 통해 해결할 수 있었다.

 

signup:1 Access to XMLHttpRequest at 'http://localhost:8080/v1/members' from origin 'http://localhost:8081' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

 

axios를 만드는 공통 js 파일에서 baseURL을 '/api'로 해주었다.

import axios from 'axios'

function createAxiosApi(){
    const axiosApi = axios.create({
        baseURL: '/api'
    })

    return axiosApi
}
const axiosApi = createAxiosApi()

export {axiosApi}

 

그리고, vue.config.js 파일에 proxy 설정을 해준다.

const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
  transpileDependencies: true,
  devServer: {
    proxy: {
      '/api': {
        target: process.env.VUE_APP_YBAF_API_URL,
        changeOrigin: true,
        pathRewrite: { '^/api': ''}
      }
    }
  }
})

 

2. 백엔드에서 처리

요청 Controller 에서 @CrossOrigin 어노테이션을 통해 간단히 해결 가능하다.

반응형