Node.js – 从 URL 读取路径参数
我们可以将路径变量嵌入到 URL 中,然后使用这些路径参数从资源中检索信息。这些 API 端点的不同值与内部传递的不同值相关。
示例 1
创建一个名为“**index.js**”的文件,并复制以下代码段。创建文件后,使用命令 “node index.js” 运行此代码。
// Reading Path parameters in Node.js
// Importing the below modules
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 received is : " + req.params.tagId);
res.send("TagId is set to " + req.params.tagId);
});
app.listen(PORT, function(error){
if (error) throw error
console.log("Server running successfully on PORT : ", PORT)
})输出
C:\home
ode>> node index.js Server running successfully on PORT: 3001 TagId received is: 1
示例 2
// Reading Path parameters in Node.js
// Importing the below modules
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("UserId is : " + user_id + " username is : "
+ username + " password is : " + password);
res.send("UserId is : " + user_id + " username is : "
+ username + " password is : " + password);
});
app.listen(PORT, function(error){
if (error) throw error
console.log("Server running successfully on PORT : ", PORT)
})输出
C:\home
ode>> node index.js Server running successfully on PORT : 3001 UserId is : 21 username is : Rahul password is : Rahul@021
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP