[英]Update a query parameter Node.js
使用 Node.js / Express 我正在定義一條路徑,傳入請求和響應。
當這條路徑被命中時,我總是想包含一個種子 url 參數,所以我將該種子查詢參數設置為 0 並重定向 url。
我接下來要做的是隨機化每個請求/響應的參數,並根據另一個 url 參數的附加更新 url,在這種情況下random=true
。
默認路由應類似於localhost:3000/default?seed=0
如果使用了random=true
參數,則路由可能類似於localhost:3000/default?seed=456&random=true
,其中種子在每個請求上都會更新。
我的代碼(server.js 使用 express、canvas 和 url 模塊):
`app.get("/default", (req, res) => {
//some logic to generate random numbers for the seed parameter
let seed = Math.round(Math.ceil(Math.random() * parseInt(req.query.seed + 1) * 100))
// if we hit the path and no seed param is defined always give it zero
if(!req.query.seed) {
req.query.seed = 0;
res.redirect(url.format({ // redirect the url with the new param
pathname: '/canvas',
query: req.query
}))
}
//if we hit the path and the random param is set to true and there is a seed parameter
if(req.query.random === 'true' && req.query.seed) {
req.query.seed = seed; // use randomized seed as the new seed param value
res.redirect(url.format({ // redirect to the url with the updated seed
pathname: '/canvas',
query: req.query
}))
//render our response
canvas(req, res);
});`
我所看到的:url 似乎正在更新,我得到如下結果:
/default?seed=115&random=true, /default?seed=21457&random=true, etc
但是我的 canvas 沒有呈現,並且我在瀏覽器localhost redirected you too many times.
我對 Node 中的重定向概念沒有深入的了解,但如果有人能指出我正確的方向以便這不再是錯誤,我將不勝感激。 謝謝
你的問題是你無限重定向。 當用戶到達/default
時,您創建查詢參數...並使用查詢參數將它們重定向回/default
,然后您再次更新查詢參數,並將它們永遠發送到/default
。 您的瀏覽器意識到您被困在一個無限循環中,並以“重定向太多”錯誤將您從它中解救出來。 您需要圍繞重定向設置中斷條件。
也許
if(!res.query){
res.redirect(url.format({ // redirect to the url with the updated seed
pathname: '/canvas',
query: req.query
}))
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.