【问题标题】:Why is req.body undefined?为什么 req.body 未定义?
【发布时间】:2022-01-05 23:09:40
【问题描述】:

这是我的代码

app.post("/hi",(req, res)=>{
    const schema = Joi.object({
        name: Joi.string().min(2).required()
    });
    const result=schema.validate(req.body);
    if(result.error){
        res.status(400).send(result.error);
        return;
    }
    console.log(req.body);


    
});

const port=process.env.PORT || 3000
app.listen(port, ()=>{
    console.log("listening on port "+port );

    
});

它只是在 localhost 的 3000 端口上侦听并将请求的主体记录到控制台中。当我通过邮递员发送任何请求时,它工作正常,除了它输出“未定义”。为什么是这样?这是我的代码问题还是我使用 Postman 的问题?

【问题讨论】:

标签: node.js request postman


【解决方案1】:

Express 默认不读取 POST 请求的正文(或任何与此相关的请求)。因此,您必须安装一些软件(通常是中间件)来识别传入请求主体的特定内容类型,从传入流中读取主体,对其进行解析并将结果放置在您期望的位置(通常是req.body)。

如果您没有任何此类中间件,则 req.body 将为空,并且请求的主体将保留在传入流中,Express 不会读取。最终,当您终止请求或传入请求超时时,它将被丢弃。

在这种情况下,您不会通过 POST 显示要发送的内容类型,但 Express 有一些内置的中间件,您可以将其用于多种类型:

// middleware to read body, parse it and place results in req.body
app.use(express.json());             // for application/json
app.use(express.urlencoded());       // for application/x-www-form-urlencoded

您只需确保适当的中间件是您的请求处理程序的一部分或安装在它之前。

如果您在此处的特定 POST 是直接来自浏览器的表单帖子,则应为 application/x-www-form-urlencoded,您可以执行以下任一操作:

// install application/x-www-form-urlencoded middleware for all
// request handlers that are defined after this one
app.use(express.urlencoded()); 

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

或者这个:

// use application/x-www-form-urlencoded middleware for this
// one request handler
app.post("/hi", express.urlencoded(), (req, res)=>{

您可以看到 Express 提供的各种类型的内容解析中间件here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-19
    • 1970-01-01
    • 2019-06-25
    • 2012-02-28
    • 2016-09-05
    相关资源
    最近更新 更多