在 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

更新於: 2022-04-06

10,000+ 次瀏覽量

開啟你的 職業生涯

完成課程即可獲得認證

開始學習
廣告
© . All rights reserved.