我们可以在Node.js中获取查询字符串中的变量吗,就像在PHP中获取$_get中的变量一样?
我知道在Node.js中,我们可以获取请求中的URL。是否有获取查询字符串参数的方法?
我们可以在Node.js中获取查询字符串中的变量吗,就像在PHP中获取$_get中的变量一样?
我知道在Node.js中,我们可以获取请求中的URL。是否有获取查询字符串参数的方法?
当前回答
白夸克反应很好。但在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'));
})
其他回答
您可以使用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)
如果您需要向IP和域发送GET请求(其他答案没有提到您可以指定端口变量),您可以使用此函数:
function getCode(host, port, path, queryString) {
console.log("(" + host + ":" + port + path + ")" + "Running httpHelper.getCode()")
// Construct url and query string
const requestUrl = url.parse(url.format({
protocol: 'http',
hostname: host,
pathname: path,
port: port,
query: queryString
}));
console.log("(" + host + path + ")" + "Sending GET request")
// Send request
console.log(url.format(requestUrl))
http.get(url.format(requestUrl), (resp) => {
let data = '';
// A chunk of data has been received.
resp.on('data', (chunk) => {
console.log("GET chunk: " + chunk);
data += chunk;
});
// The whole response has been received. Print out the result.
resp.on('end', () => {
console.log("GET end of response: " + data);
});
}).on("error", (err) => {
console.log("GET Error: " + err);
});
}
不要错过文件顶部的所需模块:
http = require("http");
url = require('url')
还要记住,您可以使用https模块通过安全域和ssl进行通信。因此这两条线将改变:
https = require("https");
...
https.get(url.format(requestUrl), (resp) => { ......
考虑一下这个url->/api/endpoint/:id?名称=萨希尔这里id是param,其中as name是查询。您可以像这样在nodejs中获取此值
app.get('/api/endpoint/:id', (req, res) => {
const name = req.query.name; // query
const id = req.params.id //params
});
//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"}
})