1. 상황
다음과 같이 출력했는데 undefined 가 나오는 경우가 있습니다.
app.post("/user", (req, res) => {
// body 출력
console.log(req.body)
res.send("ok!!!")
})
2. body-parser
body parser를 통해 파싱합니다.
1) 설치
npm i body-parser
2) 서버
const express = require('express')
const app = express()
const port = 3000
const cors = require('cors')
const bodyParser = require('body-parser')
// CORS 설정 - 모두 개방
app.use(cors());
// body parser
app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());
app.get('/', (req, res) => {
res.send("Hello World")
})
app.post("/user", (req, res) => {
// body 출력
console.log(req.body)
res.send("ok!!!")
})
app.listen(port, () => {
console.log(`${port} 포트에서 express 서버 실행`)
})
2) 클라이언트
fetch("http://localhost:3000/user", {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({id: 'HelloWorld'})
})
.then(res => {console.log('res', res)})
3) 확인
'node.js' 카테고리의 다른 글
[node] express - CORS (0) | 2022.06.03 |
---|