在node.js中检索查询字符串参数

时间:2015-11-05 07:17:44

标签: javascript node.js url-parameters restify

我正在尝试从URL检索查询字符串参数。我正在使用node.js restify模块。

网址如下所示;

http://127.0.0.1:7779/echo?UID=Trans001&FacebookID=ae67ea324&GetDetailType=FULL

提取的相关代码;

server.use(restify.bodyParser());

server.listen(7779, function () {
    console.log('%s listening at %s', server.name, server.url);
});

server.get('/echo/:message', function (req, res, next) {
    console.log("req.params.UID:" + req.params.UID);
    console.log("req.params.FacebookID:" + req.params.FacebookID);
    console.log("req.params.GetDetailType" + req.params.GetDetailType);

    var customers = [
        {name: 'Felix Jones', gender: 'M'},
        {name: 'Sam Wilson', gender: 'M'},
    ];
    res.send(200, customers);

    return next();
});

如何修改代码,以便可以从网址http://127.0.0.1:7779/echo?UID=Trans001&FacebookID=ae67ea324&GetDetailType=FULL检索req.params.UID和其他参数?

1 个答案:

答案 0 :(得分:1)

使用req.query代替req.params。你可以阅读它here

server.use(restify.bodyParser());
server.use(restify.queryParser());

server.listen(7779, function () {
    console.log('%s listening at %s', server.name, server.url);
});

server.get('/echo', function (req, res, next) {
    console.log("req.query.UID:" + req.query.UID);
    console.log("req.query.FacebookID:" + req.query.FacebookID);
    console.log("req.query.GetDetailType" + req.query.GetDetailType);

    var customers = [
        {name: 'Felix Jones', gender: 'M'},
        {name: 'Sam Wilson', gender: 'M'},
    ];
    res.send(200, customers);

    return next();
});