node.js - express 包中的app.get方法

标签 node.js express

当我运行此代码时,运行没有任何问题。

httpApp.get("/friends", function(req, res) { res.redirect("/"); });

但我想对friends.html 文件执行此操作。但没有成功。

httpApp.get("/friends.html", function(req, res) { res.redirect("/"); });

最佳答案

如果您想直接提供 .html 文件,请使用 express.static,解释见 http://expressjs.com/api.html#directory

如果不这样做,就没有理由坚持 URL 是“friends.html”,只需将其保留为“friends”即可。或者,如果您确实确实需要在 URL 中包含“friends.html”而不是静态 html 文件,请在路由中使用命名变量,将其添加到 res.locals,然后根据页面名称处理请求:

app.get(...)
app.get(...)
app.post(...)
...etc...

// specific files on / last:
app.param("file", function(req,res,next,varcontent) {
  res.locals.filename = varcontent;
  next();
});

app.get("/:file", function(req, res, next) {
  ... user res.locals.filename here ...
});

关于node.js - express 包中的app.get方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20405261/

相关文章:

node.js - 如何从 Firestore 中的查询返回结果?

node.js - Nodemon 不受 nunjucks 文件的影响

node.js - 类名jade中的变量

javascript - Nodejs - 加载一次模块并在许多不同的文件中使用

javascript - 如何在 Nodejs/Expressjs 中将多个请求分开

node.js - 我应该如何在 Node.js 中使用 Web 前端实现 RESTful API?

node.js - 尝试结束 Express js 路由中的代码执行

node.js - 如何构建我只需要打开一次 mongodb 连接的快速应用程序?

node.js - 使用 Node 和 Express 清空主体

javascript - angularjs TypeError : require(. ..)不是一个函数,nodejs运行错误