在 Express.js 中获取查询字符串变量
在 Express.js 中,你可以直接使用 req.query() 方法访问字符串变量。根据文档,req.param 方法只能获取路由参数,而 req.query 方法检查查询字符串参数。例如,"?id=12" 检查 urlencoded 正文参数。
语法
req.query( )
示例 1
创建一个名为 "reqQuery.js" 的文件并复制以下代码段。创建文件后,使用命令 "node reqQuery.js" 运行此代码,如下例所示 −
// req.query() Demo Example
// Importing the express module
var express = require('express');
// Initializing the express and port number
var app = express();
var PORT = 3000;
// Getting the request query string
app.get('/api', function(req, res){
console.log('id: ' + req.query.id)
res.send('id: ' + req.query.id);
});
// Listening to the port
app.listen(PORT, function(err){
if (err) console.log(err);
console.log("Server listening on PORT", PORT);
});输出
使用 GET 请求访问端点 "localhost:3000/api?id=21" −
C:\home
ode>> node reqQuery.js Server listening on PORT 3000 id: 21
示例 2
我们来看另一个示例。
// res.query() Demo Example
// Importing the express module
var express = require('express');
// Initializing the express and port number
var app = express();
var PORT = 3000;
// Getting the request query string
app.get('/api', function(req, res){
console.log('name: ' + req.query.id)
res.send('name: ' + req.query.id);
});
// Listening to the port
app.listen(PORT, function(err){
if (err) console.log(err);
console.log("Server listening on PORT", PORT);
});输出
使用 GET 请求访问端点 "localhost:3000/api?id=tutorialspoint"
C:\home
ode>> node reqQuery.js Server listening on PORT 3000 name: tutorialspoint
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP