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 05:08

you can use url module to collect parameters by using url.parse

var url = require('url');
var url_data = url.parse(request.url, true);
var query = url_data.query;

In expressjs it's done by,

var id = req.query.id;

Eg:

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

app.get('/login', function (req, res, next) {
    console.log(req.query);
    console.log(req.query.id); //Give parameter id
});
查看更多
伤终究还是伤i
3楼-- · 2018-12-31 05:11

For Express.js you want to do req.params:

app.get('/user/:id', function(req, res) {
  res.send('user' + req.params.id);    
});
查看更多
墨雨无痕
4楼-- · 2018-12-31 05:11

In express.js you can get it pretty easy, all you need to do in your controller function is:

app.get('/', (req, res, next) => {
   const {id} = req.query;
   // rest of your code here...
})

And that's all, assuming you are using es6 syntax.

PD. {id} stands for Object destructuring, a new es6 feature.

查看更多
弹指情弦暗扣
5楼-- · 2018-12-31 05:13

Yes you can access req.url and the builtin url module to url.parse it manually:

var url = require('url');
var url_parts = url.parse(request.url, true);
var query = url_parts.query;

However, in expressjs it's already done for you and you can simply use req.query for that:

var id = req.query.id; // $_GET["id"]
查看更多
低头抚发
6楼-- · 2018-12-31 05:14
//get query&params in express

//etc. example.com/user/000000?sex=female

app.get('/user/:id', function(req, res) {

  const query = req.query;// query = {sex:"female"}

  const params = req.params; //params = {id:"000000"}

})
查看更多
墨雨无痕
7楼-- · 2018-12-31 05:15

If you are using ES6 and Express, try this destructuring approach:

const {id, since, fields, anotherField}  = request.query;

In context:

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

app.get('/', function(req, res){
   const {id, since, fields, anotherField}  = req.query;
});

app.listen(3000);

You can use default values with destructuring, too

// sample request for testing
const req = {
  query: {
    id: '123',
    fields: ['a', 'b', 'c']
  }
}

const {
  id,
  since = new Date().toString(),
  fields = ['x'],
  anotherField = 'default'
} = req.query;

console.log(id, since, fields, anotherField)

查看更多
登录 后发表回答