Node.js – 从 URL 读取路径参数

我们可以将路径变量嵌入到 URL 中,然后使用这些路径参数从资源中检索信息。这些 API 端点相对于它们内部传递的不同值具有不同的值。

示例 1

创建一个名为“ index.js ”的文件并复制以下代码片段。创建文件后,使用命令“node index.js”运行此代码。

// 在 Node.js 中读取路径参数

// 导入以下模块
const express = require("express")
const path = require('path')
const app = express()

var PORT = process.env.port || 3001

app.get('/p/:tagId', function(req, res) {
   console.log("收到的 TagId 是: " + req.params.tagId);
   res.send("标记 ID 设置为 " + req.params.tagId);
});

app.listen(PORT, function(error){
   if (error) throw error
   console.log("服务器在 PORT 上成功运行: ", PORT)
})
输出结果
C:\home\node>> node index.js
Server running successfully on PORT: 3001
TagId received is: 1

示例 2

// 在 Node.js 中读取路径参数

// 导入以下模块
const express = require("express")
const path = require('path')
const app = express()

var PORT = process.env.port || 3001

app.get('/p/:id/:username/:password', function(req, res) {
   var user_id = req.params['id']
   var username = req.params['username']
   var password = req.params['password']

   console.log("用户 ID 是: " + user_id + " username is : "
      + username + " 密码是: " + password);
   res.send("用户 ID 是: " + user_id + " username is : "
      + username + " 密码是: " + password);
});

app.listen(PORT, function(error){
   if (error) throw error
   console.log("服务器在 PORT 上成功运行: ", PORT)
})
输出结果
C:\home\node>> node index.js
服务器在 PORT 上成功运行: 3001
用户 ID 是: 21 username is : Rahul 密码是: Rahul@021