我们可以在Node.js中获取查询字符串中的变量吗,就像在PHP中获取$_get中的变量一样?
我知道在Node.js中,我们可以获取请求中的URL。是否有获取查询字符串参数的方法?
我们可以在Node.js中获取查询字符串中的变量吗,就像在PHP中获取$_get中的变量一样?
我知道在Node.js中,我们可以获取请求中的URL。是否有获取查询字符串参数的方法?
当前回答
你应该可以这样做:
var http = require('http');
var url = require('url');
http.createServer(function(req,res){
var url_parts = url.parse(req.url, true);
var query = url_parts.query;
console.log(query); //{Object}
res.end("End")
})
其他回答
您可以使用express ^4.15.4:
var express = require('express'),
router = express.Router();
router.get('/', function (req, res, next) {
console.log(req.query);
});
希望这有帮助。
因此,有两种方式可以接收此“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);
});
对于Express.js,您需要执行req.params:
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);
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:某物
(自从我的回答以来,很多事情都发生了变化,我相信这是值得的,让事情保持最新)