As the image shown, BodyParser now is deprecated, how to correct the bodyParser syntax or statement to remove the line-through?
Asked
Active
Viewed 4.2k times
94
-
1What version of `body-parser` and `nodejs` are you using? – wiredmartian Mar 08 '21 at 06:57
-
I'm using 1.19.0 body-parser and 14.15.0 Node.js – Fu Nian Wong Mar 08 '21 at 10:29
-
9Please don't send image, prefer code : https://meta.stackoverflow.com/questions/285551/why-not-upload-images-of-code-errors-when-asking-a-question – YLR Mar 09 '21 at 05:02
3 Answers
215
If you are using Express 4.16+ you don't have to import body-parser
anymore. You can do it just like this:
app.use(express.urlencoded({extended: true}));
app.use(express.json()) // To parse the incoming requests with JSON payloads

Moath Thawahreh
- 2,519
- 2
- 14
- 19
-
7You are welcome!. And to use JSON you can just go with: app.use(express.json()) – Moath Thawahreh Mar 09 '21 at 21:33
25
Same issue occur to my projects also . Now in latest express we don't need to import body-parse, we can just use express as follow.
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
or if you limit size
app.use(express.urlencoded({ limit: "50mb", parameterLimit: 500000000 }));

Gaurav Sharma
- 261
- 2
- 4
25
Don't use body-parser
body parsing has become builtin with express
So, simply use
app.use(express.json()) //For JSON requests
app.use(express.urlencoded({extended: true}));
from directly express
You can uninstall body-parser using npm uninstall body-parser
Then you can simply get the POST content from req.body
app.post("/yourpath", (req, res)=>{
var postData = req.body;
//Or like this, for string JSON body
var postData = JSON.parse(req.body);
});

Abraham
- 12,140
- 4
- 56
- 92
-
is `JSON.parse(req.body)` really needed as long as you used `app.use(express.json())` ? I tried to use JSON object properties without `JSON.parse()` and it still works. – Sixteen Dec 08 '21 at 16:55
-
3@Sixteen Yes it works directly as long as the request has a JSON format and you won't need to use `JSON.parse()`. But for requests that send JSON in a string form, you will have to use `JSON.parse()` to get a usable JSON object. One example could be a frontend code that uses `fetch` to send request to server and sends object as string using `JSON.stringify()` – Abraham Dec 08 '21 at 20:29