Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 | 26 | 27 | 28 |
Tags
- 처음 만나는 AI수학 with Python
- 코드로배우는스프링웹프로젝트
- d
- 티스토리 쿠키 삭제
- 스프링부트핵심가이드
- 구멍가게코딩단
- 스프링 시큐리티
- 처음 만나는 AI 수학 with Python
- 친절한SQL튜닝
- 알파회계
- 자료구조와함께배우는알고리즘입문
- baeldung
- 이터레이터
- 목록처리
- 리눅스
- network configuration
- 선형대수
- 코드로배우는스프링부트웹프로젝트
- GIT
- 페이징
- 자바편
- iterator
- 자료구조와 함께 배우는 알고리즘 입문
- Kernighan의 C언어 프로그래밍
- ㅒ
- /etc/network/interfaces
- 데비안
- 네트워크 설정
- resttemplate
- 서버설정
Archives
- Today
- Total
bright jazz music
blog18 : CORS문제 해결 (server.proxy) 본문
지난 포스팅에선 아래와 같이 작성하여 서버 측에서 CORS문제를 해결하였다.
//WebConfig.java
package com.endofma.blog.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 WebConfig implements WebMvcConfigurer {
//서버에서 CORS문제를 해결하는 방법
//frontend에서 Cors문제를 해결하는 실습을 위해 주석처리
//
// @Override
// public void addCorsMappings(CorsRegistry registry) {
// registry.addMapping("/**").allowedOrigins("http://localhost:5173");
// }
}
이번에는 frontend에서 CORS문제를 해결하기 위해 주석처리 하였다.
https://vitejs.dev/config/server-options.html
Vite
Next Generation Frontend Tooling
vitejs.dev
Vue.js에서는 server.proxy를 사용하거나 API를 두어 CORS문제를 해결할 수 있다.
여기서는 server.proxy를 사용한다. 프론트로 요청이 들어왔을 때 설정된 경로로 보내는 역할을 한다.
//src/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";
// https://vitejs.dev/config/
export default defineConfig({
plugins: [vue(), vueJsx()],
resolve: {
alias: {
"@": fileURLToPath(new URL("./src", import.meta.url)),
},
},
//CORS 해결을 위해 server.proxy사용
server: {
proxy: {
"/posts": "http://localhost:8080" // /posts로 요청이 들어오면 localhost:8080으로 보낸다
}
}
});
<!-- WriteView.vue -->
<script setup lang="ts">
import {ref} from "vue"; //ref를 사용하기 위해 import
// const axios = require('axios').default; 오류발생 :CommonJS형태가 아니기 때문.
import axios from 'axios'// 따라서 이렇게 import
const title = ref("") //입력받은 값을 저장할 변수 선언
const content = ref("") //입력받은 값을 저장할 변수 선언
//WriteView.vue
const write = function() {
// axios.post("http://localhost:8080/posts",
axios.post("/posts", //전체 도메인이 아니라 path에 대한 것만 적어야 vite.config.ts에서 프록시 처리 가능.
//RequestBody
{
title: title.value,
content: content.value
});
}
</script>
<template>
<div class="mt-2">
<!-- 선언한 title, content 변수를 아래 v-model 태그에 넣는다.-->
<el-input v-model="title" placeholder="제목을 입력해 주세요"/>
</div>
<div class="mt-2">
<el-input v-model="content" type="textarea" rows="15"></el-input>
</div>
<div class="mt-2">
<el-button type="primary" @click="write()">글 작성 완료</el-button> <!--눌렀을 때 write() 함수 호출 -->
</div>
</template>
<style>
</style>
테스트 시 요청이 이상 없이 전송된다.
요청 path가 많아지는 경우.
모든 api에 대해 위처럼 개별로 해주기는 어렵다. 따라서 "/api"로 설정하여 api로 보내는 모든 요청을 중계하도록 한다.
*참고: 예제에서는 /api로 해주었지만 실제로는 다른 이름을 해주는 것이 좋다. api는 다른 api 호출에 빈번히 사용하는 용어이므로 실제 경로에 존재할 수도 있기 때문이다. api가 반드시 들어가야 하는 경로가 있다면 api가 ""이 되어버리므로 곤란해질 수 있다.
//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";
// https://vitejs.dev/config/
export default defineConfig({
plugins: [vue(), vueJsx()],
resolve: {
alias: {
"@": fileURLToPath(new URL("./src", import.meta.url)),
},
},
//CORS 해결을 위해 server.proxy사용. 또는 vue.config.js에서도 가능
server: {
proxy: {
// "/posts": "http://localhost:8080"
"/api": { //"/api"로 설정하여 api로 보내는 모든 요청을 중계하도록 한다.
target : "http://localhost:8080",
rewrite: (path) => path.replace(/^\/api/, ""),
//api로 들어온 요청에 대해, api를 ""처리하고 target으로 보내줄 수 있다.
// api로 들어온 여러 요청을 한 번에 해결할 수 있는 것이다.
},
},
},
});
<!-- WriteView.vue -->
<script setup lang="ts">
import {ref} from "vue"; //ref를 사용하기 위해 import
// const axios = require('axios').default; 오류발생 :CommonJS형태가 아니기 때문.
import axios from 'axios'// 따라서 이렇게 import
const title = ref("") //입력받은 값을 저장할 변수 선언
const content = ref("") //입력받은 값을 저장할 변수 선언
//WriteView.vue
const write = function() {
// axios.post("http://localhost:8080/posts",
// axios.post("/posts", //전체 도메인이 아니라 path에 대한 것만 적어야 vite.config.ts에서 프록시 처리 가능.
axios.post("/api/posts", //앞에 /api만 붙여주면 개별 api에 대한 처리를 vite.config.ts에서 해줄 필요 없다.
//RequestBody
{
title: title.value,
content: content.value
});
}
</script>
<template>
<div class="mt-2">
<!-- 선언한 title, content 변수를 아래 v-model 태그에 넣는다.-->
<el-input v-model="title" placeholder="제목을 입력해 주세요"/>
</div>
<div class="mt-2">
<el-input v-model="content" type="textarea" rows="15"></el-input>
</div>
<div class="mt-2">
<el-button type="primary" @click="write()">글 작성 완료</el-button> <!--눌렀을 때 write() 함수 호출 -->
</div>
</template>
<style>
</style>
'Projects > blog' 카테고리의 다른 글
blog20 : 글 내용 화면 만들기 (0) | 2023.02.04 |
---|---|
blog19 : 글 리스트 화면 만들기 (0) | 2023.02.03 |
blog17 : 글 작성화면 만들기 2 (1) | 2023.02.01 |
blog17 : 글 작성화면 만들기 1 (기초) (0) | 2023.02.01 |
blog16. Vue.js 설치 (0) | 2023.01.30 |
Comments