参数Node.js"/>
更新查询参数Node.js
使用Node.js / Express,我正在定义路径,传递请求和响应。
我总是想在点击此路径时包含种子url参数,因此我将种子查询参数设置为0并重定向了该url。
我接下来要做的是在每个请求/响应中随机分配该参数,并根据其他URL参数的附加值(在本例中为random=true
)更新URL。
默认路由应类似于localhost:3000/default?seed=0
如果使用random=true
参数,则路由可能看起来像localhost:3000/default?seed=456&random=true
,其中在每个请求上更新种子。
我的代码(使用express,canvas和url模块的server.js ::
`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
但是我的画布无法渲染,并且在浏览器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
}))
}
更多推荐
更新查询参数Node.js
发布评论