简体   繁体   English

express.js 中 req.body 的目的是什么?

[英]what is the purpose of req.body in express.js?

why req.body is called in the code为什么在代码中调用 req.body

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

req

The req object contains the request , that is, the thing the client sends to your server. req object 包含请求,即客户端发送到您的服务器的东西。

Let's look at a common HTTP request scenario:我们来看一个常见的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}

Now, let's see how we would implement this in Express:现在,让我们看看如何在 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, () => {});

See?看? req.body contains the body of the request as parsed by whatever middleware you have. req.body包含由您拥有的任何中间件解析的请求正文

In this case, the middleware stack is simple:在这种情况下,中间件堆栈很简单:

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

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

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