一切正常,直到突然发生此错误:ERR_TOO_MANY_REDIRECTS。我没有办法自己搞定,所以请帮我。
我使用express-handlebars和express路由页面,我发现问题出在哪里。在我使用res。 render ('something')的bookController文件中,无论使用哪种路由,它总是将我重定向到'/'以及何时使用res。发送( '某物')重定向到其定义的位置。
这是我的app.js文件:
const express = require("express");
const mongoose = require("mongoose");
const passport = require("passport");
const path = require("path");
const bodyParser = require("body-parser");
const hbs = require("express-handlebars");
const cookieParser = require("cookie-parser");
const session = require("express-session");
const MongoStore = require("connect-mongo")(session);
const flash = require("connect-flash");
const routes = require("./routes/index");
const expressValidator = require("express-validator");
const errorHandlers = require("./handlers/errorHandlers");
const app = express();
const webpack = require("webpack");
const webpackConfig = require("./webpack.config.js");
const compiler = webpack(webpackConfig);
const webpackDevMiddleware = require("webpack-dev-middleware")(
compiler,
webpackConfig.devServer
);
app.use(webpackDevMiddleware);
app.use(require("webpack-hot-middleware")(compiler));
app.use(express.static(path.join(__dirname, "public")));
app.engine(
"hbs",
hbs({
extname: "hbs",
defaultLayout: "main",
layoutsDir: __dirname + "/views/layouts",
partialsDir: __dirname + "/views/partials"
})
);
app.set("views", path.join(__dirname, "views"));
app.set("view engine", "hbs");
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(flash());
app.use(
session({
resave: false,
saveUninitialized: false,
secret: process.env.SECRET
})
);
app.use(cookieParser());
app.use(expressValidator());
app.use((req, res, next) => {
res.locals.flashes = req.flash();
next();
});
app.use("/", routes);
app.use(errorHandlers.flashValidationErrors);
module.exports = app;
这是我的index.js文件
const router = require("express").Router();
const bookController = require("../controllers/bookController");
const { catchErrors } = require("../handlers/errorHandlers");
router.get("/", bookController.home);
router.post("/contact", catchErrors(bookController.contactForm));
router.post("/productPage", catchErrors(bookController.productForm));
module.exports = router;
这是我的bookController文件:
const mail = require("../handlers/mail");
exports.home = async (req, res) => {
res.render("index");
};
exports.contactForm = async (req, res) => {
const email = req.body.email;
const subject = req.body.subject;
const text = req.body.text;
await mail.send({ email, subject, text });
res.redirect("/");
};
exports.productForm = async (req, res) => {
console.log(req.body);
res.redirect("/");
};
非常感谢您的帮助。 谢谢。
答案 0 :(得分:0)
解决问题的答案。
如果res.render()
没有停止请求(与res.send(html)
相同),通常意味着渲染函数出错。由于res.render()
的行为是如果出错,则会触发next(err)
。
https://expressjs.com/en/api.html#res.render
发生错误时,该方法在内部调用next(err)。
通过将回调传递给渲染器,可以很容易地在函数中跟踪错误;
res.render('index', function(err, html) {
if (err) console.error(err);
res.send(html);
});
一旦您可以跟踪并修复错误,就应该解决问题。