繁体   English   中英

更新查询参数 Node.js

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM