[英]How to handle null URL parameters with Express.js
我正在為我的 Web 服務類分配作業,但無法弄清楚如何處理空 URL 參數。 這是我的代碼:
app.get('/nachos/:x/:cheese/:tomatoes/:salsa/:hotsauce', (req, res) => {
var x = parseInt(req.params['x'])
var cheese = (req.params['cheese'])
var tomatoes = (req.params['tomatoes'])
var salsa = (req.params['salsa'])
var hotsauce = (req.params['hotsauce'])
res.send('You ordered ' + x + ' nacho(s) with ' + cheese + ', ' + tomatoes + ', ' + salsa + ', '
+ hotsauce + '.')})
此代碼在填充所有參數的情況下工作正常。 但是,如果我不想要,如何處理 null 參數,例如,salsa 並輸入 url localhost:port/nachos/1/cheese/tomatoes/hotsauce
如果我沒看錯,問題是:
如果我不想要,如何處理
null
參數,例如, salsa並輸入 urllocalhost:port/nachos/1/cheese/tomatoes/hotsauce
您不會得到null
它只是與路線不匹配。
您可以將參數設為可選,例如:
app.get('/nachos/:x?/:cheese?/:tomatoes?/:salsa?/:hotsauce?', (req, res) => {
或者添加路由來匹配,這可能會失控。
app.get([
//...
'/nachos/:x/:cheese/:tomatoes',
'/nachos/:x/:cheese/:tomatoes/:hotsauce',
'/nachos/:x/:cheese/:tomatoes/:salsa/:hotsauce',
//...
], (req, res) => {
您實際上並沒有在如下所示的路由定義中執行可選參數:
/nachos/:x/:cheese/:tomatoes/:salsa/:hotsauce
因為為了使路由匹配,每個參數都必須存在,並且req.params
包含正確的選項,它們都必須按正確的順序排列。 如果這些是變體,其中一些完全是可選的,那么按照您的方式匹配它們就不是正確的 URL 設計,並且像 Express 中那樣匹配不同的 URL 會有點痛苦。
我能想到的最簡單的方法是將可選成分放在查詢字符串中,如下所示:
/nachos/2?cheese=yes&tomatoes=yes&salsa=yes&hotsauce=yes
然后,您只需匹配路由: /nachos/:x
作為 URL 的唯一必需選項,其他所有內容都可以選擇在查詢字符串中指定,您可以編寫代碼,如果選項不是,則默認為“no”展示。 因此,沒有 hotsauce 的訂單可能是以下任一情況:
/nachos/2?cheese=yes&tomatoes=yes&salsa=yes&hotsauce=no
/nachos/2?cheese=yes&tomatoes=yes&salsa=yes
沒有辣醬或莎莎醬的訂單可能是這樣的:
/nachos/2?cheese=yes&tomatoes=yes
然后,您的請求處理程序將如下所示:
const orderOptions = ["cheese", "tomatoes", "salsa", "hotsauce"];
app.get('/nachos/:x', (req, res) => {
console.log(req.query);
let text = orderOptions.map(item => {
return req.query[item] === "yes" ? item : null;
}).filter(item => !!item).join(", ");
res.send(`You ordered ${req.params.x} nacho(s) with ${text}.`);
});
我應該提到,如果這個請求實際上是在指定一個訂單,那么它可能應該是一個 POST,而不是一個 GET,選項應該在 POST 的正文中,它們將采用與查詢字符串相同的形式,可能編碼就像application/x-www-form-urlencoded
來自表單 POST。
以這種方式傳遞參數要求 API 用戶以正確的順序發送參數。 要處理您想要的情況(缺少一種成分),您需要創建另一條路線來處理它。 但是你可以用另一種方式來做到這一點,比如將參數作為查詢字符串傳遞,甚至在請求主體上發送它們(最好是非 GET 路由器)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.