728x90
반응형
- server : node.js
- client : react.js
- data base : mongoDB
- client 부분이 없어서 포스트맨을 사용하였는데, axios를 설치하여 client 안에서 요청을 보내려고 함
npm install axios --save
- client/component/views/LadingPage/LandingPage.js
import React, {useEffect} from 'react';
import axios from 'axios';
function LandingPage(){
useEffect(() => {
axios.get('/api/hello').then(response => console.log(response.data))
}, [])
return (
<div>
LandingPage
</div>
)
}
export default LandingPage;
- server/index.js
- 엔드포인트를 api/hello로 설정하여 만들어 놓은 서버의 index.js에서 확인
app.get('/api/hello', (req,res) => {
res.send('안녕하세요~ ')
})
- server 실행
npm run backend
- client 실행
cd client
npm run start
=> 실행은 되었지만, server 포트는 6660이고, client 포트는 3000이라서 오류가 뜨는 것
** 몽고 디비 에러
=> Network Access 에서 IP를 pending 해줘야 함
- Proxy를 통해 포트 오류 해결
https://create-react-app.dev/docs/proxying-api-requests-in-development/
cd client
npm install http-proxy-middleware --save
- src/setupProxy.js 파일 생성 후 아래 코드 추가
const { createProxyMiddleware } = require('http-proxy-middleware');
module.exports = function(app) {
app.use(
'/api',
createProxyMiddleware({
target: 'http://localhost:6660',
changeOrigin: true,
})
);
};
[결과 출력]
728x90
반응형
'Web > React Node js' 카테고리의 다른 글
리액트 기초 강의 (5) - Concurrently (0) | 2022.03.01 |
---|---|
리액트 기초 강의 (4) - Proxy server (0) | 2022.03.01 |
리액트 기초 강의 (2) - Create React App & React Router Dom (0) | 2022.03.01 |
리액트 기초 강의 (1) - 기본 개념 (0) | 2022.02.28 |
노드 기초 강의 (11) - 로그아웃 기능 (0) | 2022.02.28 |
댓글