Node.js – 从 URL 读取路径参数
我们可以将路径变量嵌入到URL中,然后使用这些路径参数从资源中检索信息。这些API端点相对于它们内部传递的不同值具有不同的值。
示例1
创建一个名为“index.js”的文件并复制以下代码片段。创建文件后,使用命令“nodeindex.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