尽管我可以正确路由到正确的页面,但仍然显示我无法获取/错误。因为我的第一个路由器get(在agent.js中)在呈现表格之前先召唤一张表格,所以我不确定如何解决此问题。这是我在下面尝试过的尝试,但是无法获取/function%20router(req,%20res,%20next)%20%7B%0A%20%20%20%20router.handle(req,%20res,% 20next);%0A%20%20%7D。
如果我尝试在route.js中呈现代理页面,则该表将导致错误,因为呈现页面是在从数据库获取数据之前呈现的,并在末尾再次呈现。
app.js
const routesRouter = require("./routes/routes");
const agentRouter = require("./routes/agent");
app.use("/", routesRouter);
app.use("/agent", agentRouter);
route.js
const express = require("express");
const router = express.Router();
const agentRoute = require("./agent");
router.get("/", async function (req, res) {
res.render("login.ejs");
});
router.post("/login", async function (req, res) {
const { username, password } = req.body;
if (username == 1 && password == 1) {
res.redirect("/agent");
}
else {
return res.status(401).json({
message: "Auth fail",
});
}
router.get("/agent", async function (req, res) {
res.redirect(agentRoute);
});
});
agent.js
const express = require("express");
const router = express.Router();
const mysql = require("mysql");
const db = require("../server");
function getConnection() {
return mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database: "nodejs_login",
});
}
router.get("/agent", function (req, res, next) {
const sql = "SELECT * FROM policy1 WHERE policyAgent = 'Ron'";
db.query(sql, function (err, data, fields) {
console.log(data);
if (err) throw err;
res.render("agenthome", { title: "Policy List", policyData: data });
});
});
module.exports = router;
答案 0 :(得分:2)
在您的 agent.js 中,您仍然会得到'/ agent',这将导致 http:// localhost:3000 / agent / agent
router.get("/agent", function (req, res, next) {
const sql = "SELECT * FROM policy1 WHERE policyAgent = 'Ron'";
....
});
因此,将 agent.js 中的 router.get(“ / agent”)更改为 router.get(“ /”)文件
答案 1 :(得分:1)
您正在将重定向功能调用到路由器,这肯定不起作用。您已将app.use函数导入并调用到app.js中的agentRouter中,这应该足够
// REMOVE this code from app.js
router.get("/agent", async function (req, res) {
res.redirect(agentRoute);
});
答案 2 :(得分:0)
第1点:将route.js更改为routes.js
第2点:我想你已经用过
module.exports = router;
在route.js中