How to get GET (query string) variables in Express

2018-12-31 04:26发布

Can we get the variables in the query string in Node.js just like we get them in $_GET in PHP?

I know that in Node.js we can get the URL in the request. Is there a method to get the query string parameters?

21条回答
大哥的爱人
2楼-- · 2018-12-31 04:57
    app.get('/user/:id', function(req, res) {
      res.send('user' + req.params.id);    
    });

You can use this or you can try body-parser for parsing special element from the request parameters.

查看更多
时光乱了年华
3楼-- · 2018-12-31 04:58

Since you've mentioned Express.js in your tags, here is an Express-specific answer: use req.query. E.g.

var express = require('express');
var app = express();

app.get('/', function(req, res){
  res.send('id: ' + req.query.id);
});

app.listen(3000);
查看更多
路过你的时光
4楼-- · 2018-12-31 05:00

You should be able to do something like this:

var http = require('http');
var url  = require('url');

http.createServer(function(req,res){
    var url_parts = url.parse(req.url, true);
    var query = url_parts.query;

    console.log(query); //{Object}

    res.end("End")
})
查看更多
素衣白纱
5楼-- · 2018-12-31 05:00

I am using MEANJS 0.6.0 with express@4.16, it's good

Client:

Controller:

var input = { keyword: vm.keyword };
ProductAPi.getOrder(input)

services:

this.getOrder = function (input) {return $http.get('/api/order', { params: input });};

Server

routes

app.route('/api/order').get(products.order);

controller

exports.order = function (req, res) {
  var keyword = req.query.keyword
  ...
查看更多
若你有天会懂
6楼-- · 2018-12-31 05:00

You can use req.params with ExpressJS

router.get('/recipe/:id', function (req, res, next) {
        database.sendQuery("SELECT * FROM recipe WHERE id = " + req.params.id , function (err, results) {
            if (err) {
                console.log(err)
            } else {
                res.json(results)
            }
        })
    });
查看更多
无与为乐者.
7楼-- · 2018-12-31 05:04

It is so simple:

Example URL:

http://stackoverflow.com:3000/activate_accountid=3&activatekey=$2a$08$jvGevXUOvYxKsiBt.PpMs.zgzD4C/wwTsvjzfUrqLrgS3zXJVfVRK

You can print all the values of query string by using:

console.log("All query strings: " + JSON.stringify(req.query));

Output

All query strings : { "id":"3","activatekey":"$2a$08$jvGevXUOvYxKsiBt.PpMs.zgzD4C/wwTsvjz fUrqLrgS3zXJVfVRK"}

To print specific:

console.log("activatekey: " + req.query.activatekey);

Output

activatekey: $2a$08$jvGevXUOvYxKsiBt.PpMs.zgzD4C/wwTsvjzfUrqLrgS3zXJVfVRK

查看更多
登录 后发表回答