为什么 req.body 未定义?

nin*_*red 1 request node.js postman

这是我的代码

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 );

    
});
Run Code Online (Sandbox Code Playgroud)

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

jfr*_*d00 17

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

如果您没有任何此类中间件,则 thenreq.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
Run Code Online (Sandbox Code Playgroud)

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

如果您此处的特定帖子是直接来自浏览器的表单帖子,那么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)=>{  ... }
Run Code Online (Sandbox Code Playgroud)

或这个:

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

您可以在此处查看 Express 提供的各种类型的内容解析中间件。