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

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


当前回答

我从其他答案中吸取了教训,并决定在整个网站中使用此代码:

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

那你可以打电话

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

get的URL应该在哪里

/path/filename?id=123&option=456

其他回答

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

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

如果您正在使用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)

我使用的是MEANJS 0.6.0express@4.16,很好

客户:

控制器:

var input = { keyword: vm.keyword };
ProductAPi.getOrder(input)

服务:

this.getOrder = function (input) {return $http.get('/api/order', { params: input });};

服务器

路线

app.route('/api/order').get(products.order);

控制器

exports.order = function (req, res) {
  var keyword = req.query.keyword
  ...

2014年5月4日更新

此处保留旧答案:https://gist.github.com/stefek99/b10ed037d2a4a323d638


1) 安装express:npm安装express

应用程序.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) 运行app:node app.js

3) 在浏览器中访问:http://localhost:3000/endpoint?id=something

我收到了ID:某物


(自从我的回答以来,很多事情都发生了变化,我相信这是值得的,让事情保持最新)

在Express中,使用req.query。

req.params只获取路由参数,而不获取查询字符串参数。参见快车或帆船文档:

(req.params)检查路由参数,例如:/user/:id(req.query)检查查询字符串参数,例如:?id=12检查URL编码的主体参数(req.body),ex:id=12要使用url编码的请求体,req.body应该是一个对象。这可以通过使用_express.bodyParser中间件来完成。

也就是说,大多数时候,无论参数的来源如何,您都希望获得参数的值。在这种情况下,请使用req.param('fo')。注意,从Express 4开始,这已经被弃用:http://expressjs.com/en/4x/api.html#req.param

无论变量是在路由参数、查询字符串还是编码的请求体中,都将返回该参数的值。

附带说明-如果您的目标是获得所有三种类型的请求参数的交集(类似于PHP的$_request),您只需要将这些参数合并在一起——下面是我在Sails中如何设置的。请记住,path/route-parameters对象(req.params)具有数组财产,因此顺序很重要(尽管在Express4中可能会更改)