Programming/React+Node
따라하며 배우는 노드, 리액트 시리즈 - 기본 강의 #21 데이터 Flow & Axios
히욤이
2021. 8. 17. 03:30
axios
- react.js 부분에서 request를 보내게 되면 그때 사용할게 axios 라이브러리
- jquery를 사용할때의 ajax같은 것
axios 설치
C:\practices\react-node\boiler-plate\client> npm install axios
[client > LandingPage.js]
import React, { useEffect } from 'react';
import axios from 'axios';
export default function LandingPage() {
useEffect(() => {
axios.get('/api/hello')
.then(response => console.log(response.data));
}, [])
return(
<div>
LandingPage
</div>
)
}
request 하기 위해 임의로 만들어봄
Landing Page를 실행하자마자 useEffect 함수가 실행 됨
get Request를 server에 보낸다는 것
server에서 돌아오는 response를 console로 찍는 다는 것
[server > index.js]
app.get('/api/hello', (req, res) => {
res.send("안녕하세요~");
})
request를 받는 라우터를 index.js에서 만듬
실행시 다음과 같은 에러가 뜸
서버는 포트가 5000번이고 클라이언트는 3000번이기 때문에 서버가 request를 받지 못하고 있어 위와 같은 에러가 뜸
[LandingPage.js]
import React, { useEffect } from 'react';
import axios from 'axios';
export default function LandingPage() {
useEffect(() => {
axios.get('http://localhost:5000/api/hello')
.then(response => console.log(response.data));
}, [])
return(
<div>
LandingPage
</div>
)
}
http://localhost:5000번으로 보내줌
다른 에러가 발생 함
Access to XMLHttpRequest at 'http://localhost:5000/api/hello' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
xhr.js:177 GET http://localhost:5000/api/hello net::ERR_FAILED
createError.js:16 Uncaught (in promise) Error: Network Error
at createError (createError.js:16)
at XMLHttpRequest.handleError (xhr.js:84)