【问题标题】:what is the purpose of req.body in express.js?express.js 中 req.body 的目的是什么?
【发布时间】:2021-08-06 00:32:58
【问题描述】:

为什么在代码中调用req.body

post(function(req, res, next) {
  res.end('Will add the promotion: ' + req.body.name + ' with details: ' + req.body.description);
})

【问题讨论】:

  • 它包含请求的正文。 Express 提供正文解析器。如果正文是 JSON 数据,它会被解析并且您可以访问元素,例如req.body.namereq.body.description.
  • 欢迎来到 Stack Overflow!访问help center,使用tour 了解内容和How to Ask。请先>>>Search for related topics
  • 有问题请评论,请勿发帖。

标签: javascript node.js


【解决方案1】:

req

req 对象包含 request,即 client 发送到您的服务器的东西。

我们来看一个常见的 HTTP 请求场景:

POST /gimme-json HTTP/1.1
User-Agent: some cool user agent
Content-Type: application/json

{ "hello": "world" }
HTTP/1.1 200 OK
Content-Type: application/json

{"ok":true}

现在,让我们看看如何在 Express 中实现它:

const express = require("express");
const app = express();

// this will take the JSON bodies and put it into 'req.body'
app.use(express.json());

app.post('/gimme-json', (req, res) => {
    console.log('req.body =', req.body); // logs "req.body = { "hello": "world" }"
    res.json({ ok: true });
});

app.listen(80, () => {});

看到了吗? req.body 包含请求的正文,由您拥有的任何中间件解析。

在这种情况下,中间件堆栈很简单:

           HTTP GET
      | express internals |
      |JSON parser to body|
      |  handler for GET  |

【讨论】:

    猜你喜欢
    • 2021-12-08
    • 2012-02-28
    • 1970-01-01
    • 2020-07-11
    • 2016-01-17
    相关资源
    最近更新 更多