我们可以在Node.js中获取查询字符串中的变量吗,就像在PHP中获取$_get中的变量一样?
我知道在Node.js中,我们可以获取请求中的URL。是否有获取查询字符串参数的方法?
我们可以在Node.js中获取查询字符串中的变量吗,就像在PHP中获取$_get中的变量一样?
我知道在Node.js中,我们可以获取请求中的URL。是否有获取查询字符串参数的方法?
当前回答
通过GET方法传递参数有两种方法方法1:MVC方法,其中传递参数,如/routename/:paramname在这种情况下,您可以使用req.params.paramname获取参数值。例如,请参阅下面的代码,其中我希望Id作为参数链接可以是:http://myhost.com/items/23
var express = require('express');
var app = express();
app.get("items/:id", function(req, res) {
var id = req.params.id;
//further operations to perform
});
app.listen(3000);
方法2:常规方法:使用“?”将变量作为查询字符串传递操作人员例如,请参阅下面的代码,其中我希望Id作为查询参数链接可以是:http://myhost.com/items?id=23
var express = require('express');
var app = express();
app.get("/items", function(req, res) {
var id = req.query.id;
//further operations to perform
});
app.listen(3000);
其他回答
白夸克反应很好。但在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'));
})
通过GET方法传递参数有两种方法方法1:MVC方法,其中传递参数,如/routename/:paramname在这种情况下,您可以使用req.params.paramname获取参数值。例如,请参阅下面的代码,其中我希望Id作为参数链接可以是:http://myhost.com/items/23
var express = require('express');
var app = express();
app.get("items/:id", function(req, res) {
var id = req.params.id;
//further operations to perform
});
app.listen(3000);
方法2:常规方法:使用“?”将变量作为查询字符串传递操作人员例如,请参阅下面的代码,其中我希望Id作为查询参数链接可以是:http://myhost.com/items?id=23
var express = require('express');
var app = express();
app.get("/items", function(req, res) {
var id = req.query.id;
//further operations to perform
});
app.listen(3000);
app.get('/user/:id', function(req, res) {
res.send('user' + req.params.id);
});
您可以使用这个,也可以尝试使用主体解析器来解析请求参数中的特殊元素。
//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"}
})
因此,有两种方式可以接收此“id”:1) 使用params:代码params看起来像:假设我们有一个阵列,
const courses = [{
id: 1,
name: 'Mathematics'
},
{
id: 2,
name: 'History'
}
];
然后,对于params,我们可以执行以下操作:
app.get('/api/posts/:id',(req,res)=>{
const course = courses.find(o=>o.id == (req.params.id))
res.send(course);
});
2) 另一种方法是使用查询参数。因此url看起来像“…..\api\xyz?id=1”,其中“?id=1“是查询部分。在这种情况下,我们可以执行以下操作:
app.get('/api/posts',(req,res)=>{
const course = courses.find(o=>o.id == (req.query.id))
res.send(course);
});