我制作了一個 Express.js 系統,其中檔案/routes夾中的檔案充當經典路由(但每個路由一個檔案)
示例:/routes/get/user.js將可訪問http://localhost:8080/user(/get用于分隔方法,它可以是/post,/put...)
這是我的整個index.js檔案:https : //pastebin.com/ALtSeHXc
但實際上,我的問題是我不能像https://localhost:8080/user/random_id_here.
有了這個系統,我認為最好的辦法是找到一種方法也可以在分離的檔案上傳遞引數,但我不知道該怎么做......
這是我的一個分離檔案的示例:
module.exports = class NameAPI {
constructor(client) {
this.client = client
}
async run(req, res) {
// Code here
}
}
也許您會有更好的系統或解決方案。謝謝。
uj5u.com熱心網友回復:
我通常會設定我的快遞來處理這種情況,在這種情況下你想要一個動態插入。這是個人代碼,因此請進行必要的調整或觀察行為!:)
WEBAPP.get('/room/:name', (req, res) => {
// Check if URL ends with / (in my case I don't want that)
if (req.url.endsWith('/')) return res.redirect('/');
// Check if URL param "name" matches my regex ex. Username1920 or redirect them
if (req.params.name.match(/^[a-zA-Z0-9]{3,24}$/) === null) return res.redirect('/');
// render the room (sending EJS)
res.render('room', {
title: req.params.name.toUpperCase()
});
});
/*
/*This example accepts one param and must follow my regex/rules*/
因此,如果您收到 /room/test12345 您的 req.params.name 將回傳一個值。注意定義引數的冒號,所以你可以有 /:room/:user/:request 并且它會回傳:req.params.room, req.params.user, req.params.request 全部定義!:)
uj5u.com熱心網友回復:
您可以從已有的模塊物件中獲取可選引數,因此每個模塊都指定自己的引數。下面的這個例子展示了在模塊名稱之后添加新的引數,但是如果你需要的話,你可以擴展這個功能來更豐富。
在一個簡單的實作中,在你的加載器中,你可以改變這個:
posts.forEach((post) => {
const module = new (require(`./routes/post/${post}`))(this);
this.api.post(`/${post}`, async (req, res) => await module.run(req, res))
})
對此:
posts.forEach((post) => {
const module = new (require(`./routes/post/${post}`))(this);
const urlParams = module.params || "";
this.api.post(`/${post}${urlParams}`, async (req, res) => module.run(req, res))
});
因此,如果給定的路由想要/:id添加額外的 URL 引數,那么它只需將.urlParams其匯出的模塊物件上的屬性定義為 `"/:id" 并且將自動包含在路由定義中。
PS您的switch陳述句的每個分支中的大多數代碼_loadHttpMethode()都是相同的。通過對一個公共函式和一個或兩個傳遞給該函式的引數進行一些考慮,您可以消除開關的這些不同分支之間的所有復制代碼,因此每個開關所做的只是呼叫一個函式并傳遞幾個引數。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/405411.html
標籤:
