개발/Node.js

[Express] req.body undefined

leebera_ 2022. 5. 27. 08:58

문제점

body를 사용할 수 있도록하는 body-parser 미들웨어를 사용하지 않아 발생

(express버전이 4.16이상이라면 express에 내장되어 있음)

 

해결방법

express 4.16이상

const express = require('express');
const app = express();
​
// parse application/x-www-form-urlencoded
app.use(express.urlencoded({extended: true}));
​
// parse application/json
app.use(express.json());

 

express 4.15이하

1. body-parser 미들웨어 설치

npm i body-parser

 

2. 적용

const express = require('express');
const app = express();
const bodyParser = require('body-parser');
​
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: true }));
// parse application/json
app.use(bodyParser.json());
 

 

참고

 

Express.js req.body undefined

I have this as configuration of my Express server app.use(app.router); app.use(express.cookieParser()); app.use(express.session({ secret: "keyboard cat" })); app.set('view engine', 'ejs'); app.set("

stackoverflow.com

 

BodyParser is deprecated

As the image shown, BodyParser now is deprecated, how to correct the bodyParser syntax or statement to remove the line-through?

stackoverflow.com