24

I have the Typescript code below:

import * as express from 'express';
import * as bodyParser from 'body-parser';

...
const app: express.Application = express();

app.use(bodyParser.json());

In VSCode the bodyParser on the last line is marked with yellow squiggles saying that body-parser is deprecated.

In the .d.ts file I see the following:

/** @deprecated */
declare function bodyParser(
    options?: bodyParser.OptionsJson & bodyParser.OptionsText & bodyParser.OptionsUrlencoded,
): NextHandleFunction;

declare namespace bodyParser {
...
    function json(options?: OptionsJson): NextHandleFunction;

Why is the linter complaining about the body-parser function while I do not use it as a function in my code? Am I missing something in a tsconfig.json file to prevent this? Compiling doesn't seem to be a problem.

3
  • Is this Express? Commented Jun 15, 2020 at 20:34
  • Yes, sorry. I've added some more code lines to make that clear. Commented Jun 15, 2020 at 20:38
  • IIRC, Express.js has the function of body-parser built in since V4.16 or something like that. Commented Jun 15, 2020 at 20:39

2 Answers 2

64

BodyParse is built into Express js

So now you don't have to install body-parser, do this instead.

app.use(express.json());
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you for that, I had seen this before but didn't pay enough attention because I didn't realise it also meant that I shouldn't use the original body-parser. Still I don't understand the lint warning because the deprecation annotation is only before the function that I'm not using.
You are welcome :) , You could accept the answer so people know its a working solution
if you are looking for some popcorn eating material: github.com/expressjs/body-parser/issues/428
8

Do not use body-parser anymore

Since Express 4.16+ the body parsing functionality has become builtin with express

So, you can simply do

app.use(express.urlencoded({extended: true}));
app.use(express.json()) // To parse the incoming requests with JSON payloads

using express directly, without having to install body-parser.

uninstall body-parser using npm uninstall body-parser



Then you can access the POST data, using req.body

app.post("/yourpath", (req, res)=>{

    var postData = req.body;

    //Or if body comes as string,

    var postData = JSON.parse(req.body);
});

2 Comments

what is app and express values here?
@sam It's from the library. const express = require("express"); and const app = express();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.