请求正文 POST 来表达

request body of POST to express

我是 nodejs 和 express 的新手,在梳理一些代码时我遇到了这个,这到底是什么意思?以及如何向此发送 POST 请求(使用 cURL)?没有指定数据字段。

app.post('/', limiter, (req, res, next) => {
let {
    token
} = req.body;
if (token) {
    return res.send('congrats this is your first post request')
}
res.send('not good');
});

用过flask我大概知道是怎么回事...但是我不明白这部分

let {
    token
} = req.body;

有人可以解释一下这是怎么回事吗?无论我尝试什么,它都不接受任何 POST 请求。并且没有返回我想要的。如果这个疑问看起来太微不足道,请原谅,但我在互联网上的任何地方都没有看到这个。

也就是将req.body.token的值赋给一个名为token的变量。与这样做相同:

let token = req.body.token;

如果你想 curl 这个端点你的数据应该是 JSON 像这样:

curl -H "Content-Type: application/json" \
    -X POST \
    -d '{"token":"<your token here>"}' \
    <your url>

仅供参考:以下内容可能会有帮助。

ES2015 引入了两个重要的新 JavaScript 关键字:letconst.

这两个关键字在JavaScript.

中提供块范围变量(和常量)

ES2015之前,JavaScript只有两种作用域:全局作用域函数作用域.

通常最好养成使用 let 的习惯,以避免范围问题。

你可以找到更详细的例子here

为了后代,我在下面添加了对整个脚本的注释解释,以帮助您了解它在做什么。

/* Sets up a route in express-js */
app.post('/', limiter, (req, res, next) => {
  /* 
     Destructured Variable Assignment (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment)
     The "token" variable is copied from "token" key in "req.body" object (req.body.token). 
     You probably have bodyParser somewhere in your app that's extracting the body as a JSON for you.
  */
  let {
      token
  } = req.body;
  /* Checks "token" for truthiness */
  if (token) {
      /* sends a response (using return to exit this handler function) */
      return res.send('congrats this is your first post request')
  }
  /* Sends a response since the if statement did not call return. */
  res.send('not good');
});

这个文件等效于:

app.post('/',limiter,(req,res,next)=>{
  if (req.body.token){
    return res.send('congrats this is your first post request');
  }
  res.send('not good');
});