繁体   English   中英

请求 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 请求。 并且没有返回我想要的。 如果这个疑问看起来太微不足道,请原谅,但我还没有在 inte.net 上的任何地方看到这个。

那就是将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 中提供了Block Scope变量(和常量)。

在ES2015之前,JavaScript只有两种scope:全局ScopeFunction Scope

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

您可以在此处找到更详细的示例

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

/* 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');
});

暂无
暂无

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

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