我想要一条这样的路径:/skittles?type[]=blue&type[]=green
(就像x-www-form-urlencoded
一样,但这是对api的获取请求。)
因此,如果我有以下代码,我如何将可选参数添加到路径路径(当前/跳伞)?
app.get('/skittles', callback);
答案 0 :(得分:4)
您无需将它们添加到路径中。您可以在req.query
对象中找到它们。
var util = require('util');
app.get('/skittles', function(req, res) {
console.log(req.query);
var type = req.query.type || [];
console.log("type: "+util.inspect(type));
res.send("Type: "+util.inspect(type));
});
答案 1 :(得分:0)
您可以验证您在req.body或req.query中收到的输入请求参数。
app.post('/v1/api/test-api', function(req, res) {
var parameters = [];
if(req.body.userName !== undefined) {
//DO SOMEHTING
parameters.push({username: req.body.userName});
}
if(req.body.userId !== undefined) {
//DO SOMEHTING
parameters.push({userId: req.body.userId});
}
if(req.body.userEmail !== undefined) {
//DO SOMEHTING
parameters.push({userEmail: req.body.userEmail});
}
res.json({receivedParameters: parameters});
});