簡體   English   中英

正文解析器不適用於打字稿,當我發送請求時,我在 request.body 中得到一個 undefined

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

這是我使用 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);
        });
    }

}`

請幫我處理這部分代碼。 我不明白,為什么我在發送 post 請求時在 request.body 中未定義。

如果您運行的是 express 4.16 或更高版本,則不再需要使用 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(express.json());
            this.app.use(express.urlencoded());
            this.app.use("/", controller.router);
        });
    }

}`

請參閱此處了解更多信息: 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