Notice
Recent Posts
Recent Comments
Link
04-27 12:54
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 | 29 | 30 |
Tags
- 클라우드 서비스 개발 #
- 클라우드 서비스 개발
- Java
- HTTP
- 맥OS
- https
- 우리FIS아카데미
- 우리FIS아카데미 #
- 우리에프아이에스 #
- M2
- 글로벌소프트웨어캠퍼스
- 우리에프아이에스
- 도메인
- springboot
- route 53
- 우리FISA #
- jdk
- K-디지털트레이닝
- 맥북
- 로드밸런스
- spring
- Gradle
- 리눅스
- 우리FISA
- mysql
- sts
- 맥
- dbeaver
- AWS
Archives
- Today
- Total
<<개발일지>>
React 와 Spring 연동 본문
axios 를 활용하여 spring 의 데이터를 가져와야 하는 과제가 있었다.
axios는 fetch 함수와 다르게 json 파일로 바꿀 함수가 필요 없다. 자동으로 바꿔준다 !!
프론트(React)
import React, { useEffect, useState } from 'react'; // useEffect를 import 해야 합니다.
import DesktopCardDetail from '../components/card/detail/SelectDetail/DesktopCardDetail';
import MobileCardDetail from '../components/card/detail/SelectDetail/MobileCardDetail';
import CardList from '../components/card/detail/list/CardList';
import { useLocation } from 'react-router-dom';
import axios from 'axios';
function CardDetailList() {
const [cardDetails, setCardDetails] = useState([]);
const location = useLocation();
const { cardId } = location.state || {}; // state가 undefined일 경우를 대비한 기본값 설정
console.log(cardId); // cardId는 Object
useEffect(() => {
// useEffect 내부에서 비동기 함수를 정의하고 호출합니다.
const getData = async () => {
try {
const response = await axios.post('http://localhost:8080/api/carddetail', cardId, {
headers: {
'Content-Type': 'application/json'
}
});
console.log(response);
setCardDetails(response.data);
} catch (error) {
console.error(error);
}
};
getData(); // 비동기 함수 호출
}, [cardId]); // cardId를 의존성 배열에 추가합니다.
return (
<div>
<div className='relative flex justify-center items-center bg-gray-100 w-screen h-[100px] md:h-[400px] mt-[90px] md:mt-[90px]'>
<DesktopCardDetail />
<MobileCardDetail />
</div>
<div className='flex justify-center min-h-screen bg-gray-100'>
<CardList cardDetails={cardDetails} />
</div>
</div>
);
}
export default CardDetailList;
보내면 response를 반환하는데 axios는 response에 모든 정보가 있고 필요한 정보는 data에 있기 때문에 response.data를 해줌으로써 값을 제대로 가져올 수 있다.
백앤드(Spring)
package project.local.controller.carddetail;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import project.local.dto.CardDetailDTO.CardDetailDTO;
import project.local.dto.CardDetailDTO.CardDetailRequestDTO;
import project.local.service.carddetail.CardDetailService;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
@RequiredArgsConstructor
@RestController
public class CardDetailController {
private final CardDetailService cardDetailService;
@CrossOrigin(origins = "http://localhost:5173")
@PostMapping("/api/carddetail")
public List<CardDetailDTO> processCardDetail(@RequestBody CardDetailRequestDTO[] cardDetailRequestDTOS) {
ArrayList<CardDetailDTO> list = new ArrayList<>();
for (CardDetailRequestDTO x : cardDetailRequestDTOS) list.add(cardDetailService.findById(x.getCardId()));
return list;
}
}
이거는 react에서 보낸 요청을 spring에서 처리하는 코드이다.
@RequestBody는 프론트에서 오는 json 파일을 자동으로 원래 형태로 변환시켜준다.
이때 CROS라는 에러를 해결해주기 위해 @CrossOrigin 어노테이션을 적용해준다.
이를 적용하면 http://localhost:5173 에서 오는 요청은 허용한다는 의미가 되며 CORS 에러는 해결이 된다.
CORS에러가 생기는 경우
1. 출처가 다른 도메인 또는 포트로 리소스를 요청할 때
CORS 정책에 따라, 출처가 다른 도메인이나 포트에서 리소스를 요청하는 경우에는 브라우저에서 CORS 에러가 발생한다. 이 경우에는 서버 측에서 Access-Control-Allow-Origin 헤더를 설정하여 요청을 허용해야 한다. 이때 사용하는 어노테이션이 CrossOrigin이다.
'React' 카테고리의 다른 글
Babel (0) | 2023.12.17 |
---|---|
Context API (1) | 2023.12.17 |
JSX 란 (0) | 2023.12.09 |
커스텀 Component 구현 (1) | 2023.12.08 |
컴포넌트 기반 페이지 기획, 개발 (0) | 2023.12.08 |