简体   繁体   中英

Body-parser doesn't work with typescript, when I send a request, I'm getting an undefined in request.body

Here is my following code of my express application with typescript 3.7.4:

import bodyParser from "body-parser";
import config from "config";
import cookieParser from "cookie-parser";
import express from "express";
import mongoose from "mongoose";
import path from "path";

export default class App {

    public app: express.Application;

    constructor() {
        this.app = express();
        this.initializeMiddlewares();
    }

    public listen(port: any) {
        this.app.listen(port, () => {
            console.log(`App listening on the port ${port}`);
        });
    }

    public initializeControllers(controllers: any) {
        controllers.forEach((controller: any) => {
            this.app
                .use(bodyParser.json())
                .use(bodyParser.urlencoded())
                .use("/", controller.router);
        });
    }

}`

Please, help me with this part of code. I don't understand, why I'm getting undefined in request.body, when i'm sending post request.

If you are running express 4.16 or greater, you no longer need to use body-parser.

You can try doing this instead:

import config from "config";
import cookieParser from "cookie-parser";
import express from "express";
import mongoose from "mongoose";
import path from "path";

export default class App {
    
    public app: express.Application;

    constructor() {
        this.app = express();
        this.initializeMiddlewares();
    }

    public listen(port: any) {
        this.app.listen(port, () => {
            console.log(`App listening on the port ${port}`);
        });
    }

    public initializeControllers(controllers: any) {
        controllers.forEach((controller: any) => {
            this.app.use(express.json());
            this.app.use(express.urlencoded());
            this.app.use("/", controller.router);
        });
    }

}`

See here for more info: https://medium.com/@mmajdanski/express-body-parser-and-why-may-not-need-it-335803cd048c

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM