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:04

Getting Any URL Parameter

For this example, we'll grab a parameter directly from the URL.

Let's say we are using the example URL: http://example.com/api/users/?id=4&token=sdfa3&geo=us

The parameters that come out of this will be:

id 4

token sdfa3

geo us

It's very easy to grab these parameters. Here's the route and the method for grabbing parameters is req.param().

// routes will go here

app.get('/api/users', function(req, res) {
  var user_id = req.query.id;
  var token = req.query.token;
  var geo = req.query.geo;  

  res.send(user_id + ' ' + token + ' ' + geo);
});

The parameters are naturally passed through the req (request) part.

Now if we go to our browser at http://localhost:8080/api/users/?id=4&token=sdfa3&geo=us

we'll be able to see the three parameters!

查看更多
心情的温度
3楼-- · 2018-12-31 05:06

UPDATE 4 May 2014

Old answer preserved here: https://gist.github.com/stefek99/b10ed037d2a4a323d638


1) Install express: npm install express

app.js

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

app.get('/endpoint', function(request, response) {
    var id = request.query.id;
    response.end("I have received the ID: " + id);
});

app.listen(3000);
console.log("node express app started at http://localhost:3000");

2) Run the app: node app.js

3) Visit in the browser: http://localhost:3000/endpoint?id=something

I have received the ID: something


(many things have changed since my answer and I believe it is worth keeping things up to date)

查看更多
冷夜・残月
4楼-- · 2018-12-31 05:06

A small Node.js HTTP server listening on port 9080, parsing GET or POST data and sending it back to the client as part of the response is:

var sys = require('sys'),
url = require('url'),
http = require('http'),
qs = require('querystring');

var server = http.createServer(

    function (request, response) {

        if (request.method == 'POST') {
                var body = '';
                request.on('data', function (data) {
                    body += data;
                });
                request.on('end',function() {

                    var POST =  qs.parse(body);
                    //console.log(POST);
                    response.writeHead( 200 );
                    response.write( JSON.stringify( POST ) );
                    response.end();
                });
        }
        else if(request.method == 'GET') {

            var url_parts = url.parse(request.url,true);
            //console.log(url_parts.query);
            response.writeHead( 200 );
            response.write( JSON.stringify( url_parts.query ) );
            response.end();
        }
    }
);

server.listen(9080);

Save it as parse.js, and run it on the console by entering "node parse.js".

查看更多
余欢
5楼-- · 2018-12-31 05:06

Whitequark responded nicely. But with the current versions of Node.js and Express.js it requires one more line. Make sure to add the 'require http' (second line). I've posted a fuller example here that shows how this call can work. Once running, type http://localhost:8080/?name=abel&fruit=apple in your browser, and you will get a cool response based on the code.

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

app.configure(function(){
    app.set('port', 8080);
});

app.get('/', function(req, res){
  res.writeHead(200, {'content-type': 'text/plain'});
  res.write('name: ' + req.query.name + '\n');
  res.write('fruit: ' + req.query.fruit + '\n');
  res.write('query: ' + req.query + '\n');
  queryStuff = JSON.stringify(req.query);
  res.end('That\'s all folks'  + '\n' + queryStuff);
});

http.createServer(app).listen(app.get('port'), function(){
    console.log("Express server listening on port " + app.get('port'));
})
查看更多
临风纵饮
6楼-- · 2018-12-31 05:06

You can use

request.query.<varible-name>;
查看更多
有味是清欢
7楼-- · 2018-12-31 05:07

You can use with express ^4.15.4:

var express = require('express'),
    router = express.Router();
router.get('/', function (req, res, next) {
    console.log(req.query);
});

Hope this helps.

查看更多
登录 后发表回答