我们可以在Node.js中获取查询字符串中的变量吗,就像在PHP中获取$_get中的变量一样?
我知道在Node.js中,我们可以获取请求中的URL。是否有获取查询字符串参数的方法?
我们可以在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)
其他回答
//get query¶ms in express
//etc. example.com/user/000000?sex=female
app.get('/user/:id', function(req, res) {
const query = req.query;// query = {sex:"female"}
const params = req.params; //params = {id:"000000"}
})
对于Express.js,您需要执行req.params:
app.get('/user/:id', function(req, res) {
res.send('user' + req.params.id);
});
app.get('/user/:id', function(req, res) {
res.send('user' + req.params.id);
});
您可以使用这个,也可以尝试使用主体解析器来解析请求参数中的特殊元素。
既然您在标签中提到了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);
可以使用url.parse使用url模块收集参数
var url = require('url');
var url_data = url.parse(request.url, true);
var query = url_data.query;
在expressjs中,
var id = req.query.id;
Eg:
var express = require('express');
var app = express();
app.get('/login', function (req, res, next) {
console.log(req.query);
console.log(req.query.id); //Give parameter id
});