简体   繁体   中英

Update a query parameter Node.js

using Node.js / Express I am defining a path, passing in a request and response.

I always want to include a seed url parameter when this path is hit so I set that seed query param to 0 and redirect the url.

What I want to do next is randomize that parameter with each request/response and update the url based on the additional of another url param, in this case random=true .

Default route should look like localhost:3000/default?seed=0

Route if the random=true parameter is used could look like localhost:3000/default?seed=456&random=true where the seed is updated on each request.

My code (server.js using express, canvas, and url modules):

`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);
});`

What I see: The url does appear to be updating I get results such as:

/default?seed=115&random=true, /default?seed=21457&random=true, etc

However my canvas does not render and I get a too many redirects error in the browser localhost redirected you too many times.

I don't have a great knowledge of redirect concepts in Node but would appreciate it if someone could point me in the right direction so that this is no longer an error. Thanks

Your issue is you are infinitely redirecting. When the user arrives at /default you create your query params... and redirect them back to /default with the query params, where you then again update the query params, and send them to /default forever. Your browser realizes you're trapped in an infinite loop and breaks you out of it with the "too many redirects" error. You need a break condition around your redirect.

Maybe

if(!res.query){
   res.redirect(url.format({ // redirect to the url with the updated seed
      pathname: '/canvas',
      query: req.query
   }))
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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