Forwarding redirection when using Express.js routers

When using Express Routers, a route prefix can be provided:

var router = new Express.Router();
app.use("/scope", router);

      

Let's say I have multiple CRUD paths in my router.

router.post("/", function(req, res) {
  var result = create(req);
  res.redirect(result.id);
});

router.put("/:id", function(req, res) {
  var result = update(req);
  res.redirect(result.id);
});

router.get("/:id", function(req, res) {
  var result = findById(req.params.id);
  res.render("show.html", {data: result});
});

      

When requesting a PUT above, the response will be redirected to "/ scope / [id]", as it should. On a POST request, the response is a redirect to "/ [id]" instead of the previous result.

I'm not sure where to find the root of the problem and how to fix it.

+3


source to share


1 answer


Anyway, I'll answer the question, for the benefit of anyone who might come across this issue.

I suspect that your original problem was that since you had strict mode disabled (Express by default), your client side code was most likely POSTING to /scope' (which in non-strict node is the same as

/ scope / ). Within your post handler you did a relative redirect using

res.redirect (result.id ) . Let say

result.id is

123 , then a relative redirect would take you to

/ 123`.



NOTE. Don't forget that Express has little to do with the actual redirects that the browser takes care of on the client side.

The problem could easily have been solved by ensuring your client-side code is POSTed before /scope/

, after which a relative redirect id

will take you to /scope/id

, as expected.

0


source







All Articles