Node.js:如何在POST中传递params?

时间:2011-08-13 22:14:51

标签: javascript node.js express

我有快递应用和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应该不起作用吗?

由于

4 个答案:

答案 0 :(得分:4)

不,您传递的参数不在帖子正文中,而是在查询字符串中。

根据the docs,要访问它,您必须执行以下操作:

req.query.user

答案 1 :(得分:4)

所选答案错误。很明显你想要一些来自请求体的东西(假设你说POST),而不是查询字符串。您需要确保正文解析器位于中间件堆栈中:

app.use(express.bodyParser());

执行此操作后,您可以使用req.body

(此外,正如其他人所提到的,你的卷曲也是错误的。你在查询字符串中放入了一些东西而不是请求体。)

答案 2 :(得分:1)

没有,这是行不通的,因为你正在将URL添加到URL(这就是你要为GET做的事情)。对于您需要的帖子:

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

答案 3 :(得分:1)

不,卷曲调用是错误的。试试

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