我使用 Express 为 MVC 模式编写 CRUD API。
将模板应用到 CRUD API 时出现问题。
我使用索引 View 作为根路径。但是,无论索引 View 中的链接如何,都会显示相同的 View 。对于根路径以外的所有访问,我都会收到 304 状态代码
。
有人可以帮我找到这个问题的根源吗?
app.js
...
const post = require("./routes/post");
app.use("/", (req, res) => {
res.render("index");
});
app.use("/posts", post);
...
index.pug
doctype html
html
head
meta(charset='UTF-8')
body
a(href='/posts/new') new
路线
const postsController = require("../controller/posts_controller");
router.get("/new", postsController.post_new);
Controller
exports.post_new = (req, res, next) => {
res.render("new");
};
最佳答案
Express 按照定义的顺序检查路由,并使用其路由与传入请求的路径匹配的第一个处理程序。由于您将根路由 ("/"
) 放在顶部,并且所有路由(至少)都与根路由匹配,因此它将匹配并处理传入的任何请求。
要解决此问题,您可以将根路由的定义移至 app.js 的末尾。例如:
const post = require("./routes/post");
app.use("/posts", post);
app.use("/", (req, res) => {
res.render("index");
});
一般来说,您应该在其父路由之前定义子路由,并在具有相同位置的变量的路由之前定义具有静态值的路由。因此,一个很好的示例订单是:
app.use("/posts/new", ...);
app.use("/posts/:id", ...);
app.use("/posts", ...);
app.use("/", ...);
关于node.js - 304 状态代码出现在 Node Express 应用程序中除根路径之外的所有路径中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55329544/