[오늘의 공부]/Node.js & package manager
[오늘의 node.js] mongoose+mongoDB+express쓰기 / proxy 설정하기
돈워리비해삐
2023. 3. 5. 01:48
Proxying API Requests in Development | Create React App
Note: this feature is available with react-scripts@0.2.3 and higher.
create-react-app.dev
3000번 포트 -> 5000번 포트 서버 응답받기
react 폴더
npm i http-proxy-middleware --save
react > src > setupProxy.js
const { createProxyMiddleware } = require('http-proxy-middleware');
module.exports = (app) => {
app.use(
'/api',
createProxyMiddleware({
target: 'http://localhost:5000',
changeOrigin: true,
})
);
};
프론트에서 서버요청
react > src > App.js
import axios from "axios";
import { useEffect } from "react";
function App() {
const item = {
name: "react",
};
useEffect(() => {
axios
.post("./api/send", item)
.then((res) => {
console.log(res);
})
.catch((err) => {
console.log(err);
});
}, []);
return (
<div>
<h1>리액트, node 연습</h1>
</div>
);
}
export default App;
서버에서 클라이언트쪽 요청을 받아 응답
node > index.js
const express = require('express');
const path = require('path');
const mongoose = require('mongoose');
const app = express();
const port = 5000;
app.use(express.static(path.join(__dirname, '../react/build')));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.listen(port, () => {
mongoose
.connect(
'mongodb앱키'
)
.then(() => {
console.log(`Server app listening on port ${port}`);
console.log('Connecting MongoDB...');
})
.catch((err) => {
console.log(err);
});
});
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, '../react/build/index.html'));
});
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, '../react/build/index.html'));
});
//react로부터 받은 요청처리
app.post('/api/send', (req, res) => {
console.log(req.body);
res.status(200).json({ success: true, result: req.body.name + '2' });
});