简体   繁体   English

正文解析器不适用于打字稿,当我发送请求时,我在 request.body 中得到一个 undefined

[英]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:这是我使用 typescript 3.7.4 编写的 Express 应用程序的以下代码:

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.我不明白,为什么我在发送 post 请求时在 request.body 中未定义。

If you are running express 4.16 or greater, you no longer need to use body-parser.如果您运行的是 express 4.16 或更高版本,则不再需要使用 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请参阅此处了解更多信息: https : //medium.com/@mmajdanski/express-body-parser-and-why-may-not-need-it-335803cd048c

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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