簡體   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