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
廣告