Front/Vue.js

프록시를 통한 CORS 프론트에서 해결하기

제우제우 2024. 8. 22. 22:16

vite.config.ts

import { fileURLToPath, URL } from 'node:url'

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import vueJsx from '@vitejs/plugin-vue-jsx'
import vueDevTools from 'vite-plugin-vue-devtools'

export default defineConfig({
  plugins: [
    vue(),
    vueJsx(),
    vueDevTools(),
  ],
  resolve: {
    alias: {
      '@': fileURLToPath(new URL('./src', import.meta.url))
    }
  },
  server: {
    proxy: {
      "/api": {
        target: "http://localhost:8080",
        rewrite: (path) => path.replace(/^\/api/, ""),
      },
    },
  },
})

 

proxy 설정 이유 

프론트엔드 애플리케이션이 백엔드 서버에 요청을 보낼 때 동일 출처 정책(Same-Origin Policy)으로 인해 발생하는 CORS 문제를 우회하기 위해 프록시를 설정했다. 

 

동작 방식 

프론트엔드 애플리케이션에서 /api로 시작하는 요청이 있을 경우, 해당 요청을 프론트 서버가 백엔드 서버

(http://localhost:8080)로 프록시(대리)하여 전달 

이렇게 하면 브라우저는 실제 백엔드와 통신하는 대신, 동일 출처로 간주되는 프론트엔드 개발 서버를 통해 요청을 보내게 된다. 

 

target 

프록시 요청을 보낼 백엔드 주소를 지정 여기서는 http://localhost:8080이 백엔드 서버로 설정

즉 모든 /api로 시작하는 요청은 이 서버로 전달 

 

rewrite 

rewrite 함수는 요청 경로에서 /api를 제거 ex) 클라이언트가 /api/posts로 요청을 보내면 이 경로는 프록시 서버에 의해서

http://localhost:8080/posts로 변경되어 백엔드 서버로 전달된다. 

 

테스트

먼저 백엔드 서버에서 CORS 설정 처리를 없앴다. & 서버 재시작 

// @Configuration
public class WebConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("http://localhost:5173");
    }
}

 

글 작성 VIEW

<script setup lang="ts">
import {ref} from "vue";
import axios from 'axios'; // axios 라이브러리 import

const title = ref("")
const content = ref("")

const write = function(){
  // console.log(title.value, content.value)
  axios.post("/api/posts", {
      title: title.value,
      content: content.value
  });
}
</script>

<template>
  <div>
    <el-input v-model="title" placeholder="제목을 입력해주세요" />
  </div>

  <div class="mt-2">
    <el-input v-model="content" placeholder="내용을 입력해주세요" type="textarea" rows="15"/>
  </div>

  <div class="mt-2">
  <el-button type="primary" @click="write()">글 작성완료</el-button>
  </div>
</template>

<style>
</style>

 

실행 결과 

 

'Front > Vue.js' 카테고리의 다른 글

[Vue.js] 시작, Element Plus, Bootstrap  (0) 2024.08.22