Search code examples
javascriptnode.jsurl-parametersrestify

Retrieve query string parameters in node.js


I am trying to retrieve query string parameters from a URL. I am using node.js restify module.

The URL looks like this;

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

The extracted relevant code;

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();
});

How can the code be modified so that req.params.UID and the other parameters can be retrieved from the URL http://127.0.0.1:7779/echo?UID=Trans001&FacebookID=ae67ea324&GetDetailType=FULL?


Solution

  • Use req.queryinstead of req.params. You can read about it 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();
    });