我正在使用Passport在NodeJS上验证我的用户。目前我正在使用ExpressJS,我正试图路由我的流量。我目前使用以下代码:
website.js(主档案)
require("./routes.js")(app);
routes.js
var pages = {
home: require("./pages/home"),
about: require("./pages/about"),
register: require("./pages/register"),
login: require("./pages/login"),
api: require("./api/index")
};
module.exports = function(app) {
app.use("/", pages['home']);
for (page in pages) {
app.use("/" + page, pages[page]);
}
app.get("/logout", function(req, res) {
req.logout();
req.redirect("/");
});
}
register.js
var express = require('express');
var router = express.Router();
var app = express();
router.get("/", function(req, res) {
res.render("register", { page: "Register", message: req.flash("registerMessage") });
});
app.post("/", passport.authenticate("register", {
successRedirect: "/about/",
failureRedirect: "/register/",
failureFlash: true,
successFlash: "Logged in!"
}));
module.exports = router;
我面临的问题是对此的POST请求将导致404.找不到该页面。 GET请求(so / register)正确显示注册表单,但在提交时我得到404.如果我将router.get("/", function(req,res){})
更改为router.use("/", function(req, res, next) {})
,当我调用“Next()时,我将收到HTTP 500错误“(发送后无法设置标题。),POST仍无效。
有人能告诉我如何正确捕获路由器中间件后面的POST请求吗?
答案 0 :(得分:-1)
我使用以下方法解决了我的问题:
router.route("/")
.get(function(req, res, next) {
res.render("register", { page: "Register", message: req.flash("registerMessage") });
})
.post(passport.authenticate("register", {
successRedirect: "/about/",
failureRedirect: "/register/",
failureFlash: true,
successFlash: "Logged in!"
}));