簡體   English   中英

Node.js:如何在 POST 中傳遞參數?

[英]Node.js: How to pass params in a POST?

我有一個快速應用程序和一個 POST 路由:

app.post('/test', function(req, res){

 //res.send(req.body.title + req.body.body)
 console.log(req.params);
 console.log(req.body);
 console.log(req.body.user);
 console.log(req.body.feedback);
 console.log("ok");
 //return;
});

我嘗試做 ~ $ curl -X POST "http://xxxx.herokuapp.com/test?user=hello"我得到:

TypeError: Cannot read property 'user' of undefined
    at Router.<anonymous> (/app/app.js:40:22)
    at done (/app/node_modules/express/lib/router/index.js:250:22)
    at middleware (/app/node_modules/express/lib/router/index.js:244:9)
    at param (/app/node_modules/express/lib/router/index.js:227:11)
    at pass (/app/node_modules/express/lib/router/index.js:232:6)
    at Router._dispatch (/app/node_modules/express/lib/router/index.js:255:4)
    at Object.handle (/app/node_modules/express/lib/router/index.js:45:10)
    at next (/app/node_modules/express/node_modules/connect/lib/http.js:198:15)
    at Object.methodOverride [as handle] (/app/node_modules/express/node_modules/connect/lib/middleware/methodOverride.js:35:5)
    at next (/app/node_modules/express/node_modules/connect/lib/http.js:198:15)~ $ 

POST不應該工作嗎?

謝謝

不,您傳遞的參數不在帖子正文中,而是在查詢字符串中。

根據文檔,要訪問它,您必須執行以下操作:

req.query.user

選擇的答案是錯誤的。 很明顯,您想從請求正文中獲取一些東西(假設您說的是 POST),而不是查詢字符串。 您需要確保正文解析器在您的中間件堆棧中:

app.use(express.bodyParser());

完成此操作后,您可以使用req.body

(此外,正如其他人所提到的,您的 curl 也是錯誤的。您將某些內容放在查詢字符串中而不是請求正文中。)

不,那是行不通的,因為您將 args 添加到 URL (這就是您為 GET 所做的)。 對於帖子,您需要:

curl -d "user=hello" http://xxxx.herokuapp.com/test

不,curl 調用是錯誤的。 嘗試

curl -X POST "http://xxxx.herokuapp.com/test" -d user=hello

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM