使用 Express 路由器时,可以提供路由前缀:
var router = new Express.Router();
app.use("/scope", router);
假设我的路由器中有一些 CRUD 路由。
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});
});
当请求上面的 PUT 时,响应应该是重定向到“/scope/[id]”。当请求 POST 时,响应是重定向到“/[id]”而不是之前的结果。
我不确定在哪里找到问题的根源,也不知道如何纠正它。
最佳答案
无论如何,为了其他可能遇到此问题的人的利益,我会回答这个问题。
我怀疑您最初的问题是,由于您禁用了严格模式(Express 的默认设置),您的客户端代码可能会 POST 到 /scope' (which in non-strict node is the same as
/范围/). Within your post handler you did a relative redirect using
res.redirect(result.id) . Let say
结果.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, which are taken care of client-side by the browser.
通过确保您的客户端代码发布到/scope/
,这个问题可以很容易地解决。 ,之后相对重定向到 id
会带您到/scope/id
,正如您所期望的那样。
关于redirect - 使用 Express.js 路由器时的范围重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29755225/