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

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


当前回答

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

其他回答

白夸克反应很好。但在Node.js和Express.js的当前版本中,它还需要一行代码。确保添加“require-http”(第二行)。我在这里发布了一个更完整的示例,展示了此呼叫的工作原理。运行后,键入http://localhost:8080/?name=abel&fruit=apple在浏览器中,您将根据代码得到一个很酷的响应。

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'));
})

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

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

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.js中,你可以很容易地得到它,你需要在控制器函数中做的就是:

app.get('/', (req, res, next) => {
   const {id} = req.query;
   // rest of your code here...
})

仅此而已,假设您使用的是es6语法。

PD.{id}代表Object destructuring,一个新的es6特性。

您可以使用

request.query.<varible-name>;