CORS(Cross-Origin Resource Sharing)란?
교차 출처 리소스 공유를 의미한다. 브라우저가 다른 출처의 리소스를 로딩할 수 있도록 서버가 허가하는 HTTP 헤더 기반의 메커니즘이다.
먼저 spring boot에 configuration을 만들어준다.
package com.findMyBook.backend.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 {
@Override
public void addCorsMappings(CorsRegistry corsRegistry) {
// CORS 설정: React 프론트엔드에서 오는 요청을 허용
corsRegistry.addMapping("/**")
.allowedOrigins("http://localhost:3000") // React 개발 서버
.allowedMethods("GET", "POST", "PUT", "DELETE")
.allowedHeaders("*");
}
}
다음으로 RestController를 만들어준다. 가볍게 hello정도
package com.findMyBook.backend.controller;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RequestMapping("/api")
@RestController
public class FetchController {
@GetMapping("/hello")
public ResponseEntity<String> getHello() {
return ResponseEntity.ok("Hello, World!");
}
}
이제 Next package.json에 "proxy": "http://localhost:8080",를 추가한다.
package.json 파일에 "proxy": "http://localhost:8080"를 설정하는 것은 React 개발 서버에서 백엔드 서버로의 요청을 우회(proxy)하도록 설정하는 것이다.
- proxy 설정을 꼭 해야 하는 경우: React 앱과 Spring Boot 서버가 다른 포트에서 실행되고 있으며, CORS 문제를 우회하려는 경우
- proxy 설정을 하지 않아도 되는 경우:백엔드(Spring Boot)에서 CORS 설정을 잘 처리했다면, 프론트엔드에서 proxy를 사용하지 않고도 정상적으로 요청을 보낼 수 있다. 프론트엔드와 백엔드가 같은 도메인에서 실행되는 경우에도 proxy 설정은 필요하지 않다.
{
"name": "frontend",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev --turbopack",
"build": "next build",
"start": "next start",
"lint": "next lint"
},
"dependencies": {
"axios": "^1.7.9",
"browser-fs-access": "^0.35.0",
"clsx": "^2.1.1",
"framer-motion": "^11.18.1",
"glob": "^11.0.1",
"next": "15.1.4",
"path-scurry": "^2.0.0",
"react": "^19.0.0",
"react-dom": "^19.0.0",
"react-dropzone": "^14.3.5",
"slate": "^0.112.0",
"slate-react": "^0.112.1",
"swiper": "^11.2.1"
},
"proxy": "http://localhost:8080",
"devDependencies": {
"@eslint/eslintrc": "^3",
"@types/node": "^20",
"@types/react": "^19",
"@types/react-dom": "^19",
"eslint": "^9",
"eslint-config-next": "15.1.4",
"postcss": "^8",
"tailwindcss": "^3.4.1",
"typescript": "^5"
}
}
다음 page.tsx 에서 axios나 fetch 등으로 요청한다.
'use client';
import { MainSwiper } from '@/components/main/swiperMain';
import { Menu } from '@/components/main/menu';
import axios from 'axios';
export default function Home() {
// axios({
// method: 'get',
// url: 'http://localhost:8080/api/hello',
// // headers: {
// // 'Content-Type': 'application/json',
// // },
// })
axios
.get('http://localhost:8080/api/hello')
.then((response) => console.log(response))
.catch((error) => {
console.log(error);
});
return (
<div className="flex gap-6 h-5/6 mt-6 md:flex-col md:gap-2 md:mt-2 md:h-full ">
<div className="border border-gray-300 w-80 h-full bg-white rounded-2xl py-12 lg:hidden">
<Menu />
<h1 className="text-2xl font-bold"></h1>
</div>
<div className="border border-gray-300 w-full bg-white rounded-2xl overflow-y-auto">
<MainSwiper title="최신 등록" />
<MainSwiper title="가장 많이 본" />
</div>
</div>
);
}
hello world가 콘솔에 찍히고 200(성공)이면 성공이다.
'JavaScript > Next' 카테고리의 다른 글
| Drizzle ORM (0) | 2025.02.12 |
|---|---|
| Neon (0) | 2025.02.12 |
| Clerk (0) | 2025.02.12 |
| ShadCN/UI & Lucide React 사용하기 (0) | 2025.02.12 |
| [Next] next 시작하기(폴더 구조, use client와 server) (0) | 2025.02.12 |