How to get GET (query string) variables in Express.js on Node.js?

前端 未结 26 3522
庸人自扰
庸人自扰 2020-11-21 23:53

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.

相关标签:
26条回答
  • 2020-11-22 00:06

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

    app.get('/user/:id', function(req, res) {
      res.send('user' + req.params.id);    
    });
    
    0 讨论(0)
  • 2020-11-22 00: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.

    0 讨论(0)
  • 2020-11-22 00:07

    It actually simple:

    const express= require('express');
    const app = express();
    
    app.get('/post', (req, res, next) => {
      res.send('ID:' + req.query.id + ' Edit:'+ req.query.edit);
    });
    
    app.listen(1000);
    
    // localhost:1000/post?id=123&edit=true
    // output: ID: 123 Edit: true
    
    0 讨论(0)
  • 2020-11-22 00:09

    I learned from the other answers and decided to use this code throughout my site:

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

    Then you can just call

    var id = query.id;
    var option = query.option;
    

    where the URL for get should be

    /path/filename?id=123&option=456
    
    0 讨论(0)
  • 2020-11-22 00:09

    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'));
    })
    
    0 讨论(0)
  • 2020-11-22 00:10

    In Express it's already done for you and you can simply use req.query for that:

    var id = req.query.id; // $_GET["id"]
    

    Otherwise, in NodeJS, 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;
    
    0 讨论(0)
提交回复
热议问题