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

前端 未结 26 3497
庸人自扰
庸人自扰 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: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'));
    })
    

提交回复
热议问题