我们可以在Node.js中获取查询字符串中的变量吗,就像在PHP中获取$_get中的变量一样?

我知道在Node.js中,我们可以获取请求中的URL。是否有获取查询字符串参数的方法?


当前回答

您可以使用express ^4.15.4:

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

希望这有帮助。

其他回答

如果您正在使用ES6和Express,请尝试以下销毁方法:

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

在上下文中:

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

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

app.listen(3000);

也可以在析构函数中使用默认值:

//测试样品请求常量要求={查询:{id:'123',字段:[a','b','c']}}常量{身份证件,since=new Date().toString(),字段=['x'],anotherField='默认'}=请求查询;console.log(id,since,fields,anotherField)

表达特定的简单获取方法

查询字符串(在?之后),例如https://...?user=abc&id=123var express=要求('express');var app=express();app.get('/',函数(req,res){res.send('id:'+req.query.id);});app.listen(3000);查询参数,如https://.../get/users/:idvar express=要求('express');var app=express();app.get('/get/users/:id',函数(req,res){res.send('id:'+req.params.id);});app.listen(3000);

你应该可以这样做:

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")
})

如果您想避免表达,请使用以下示例:

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

function func111(req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  var q = url.parse(req.url, true);
  res.end("9999999>>> " + q.query['user_name']); 
}

http.createServer(func111).listen(3000); 

用法:

curl http://localhost:3000?user_name=user1

通过yl

既然您在标签中提到了Express.js,这里有一个Express特有的答案:使用req.query。

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

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

app.listen(3000);