【问题标题】:Unable to route despite having router.get尽管有 router.get 仍无法路由
【发布时间】:2020-08-03 14:11:56
【问题描述】:

虽然我有正确的页面路由,但它仍然显示我无法获取/错误。因为我的第一个路由器 get(在 agent.js 中)在渲染表之前调用了一个表,所以我不确定如何解决这个问题。这是我在下面尝试过的尝试,但我得到了一个 cannot GET /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;

【问题讨论】:

    标签: html node.js


    【解决方案1】:

    在您的 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("/")文件

    【讨论】:

      【解决方案2】:

      您正在向绝对不起作用的路由器调用重定向功能。您已经在 app.js 中向 agentRouter 导入并调用了 app.use 函数,这应该足够了

      // REMOVE this code from app.js
      router.get("/agent", async function (req, res) {    
        res.redirect(agentRoute);
      });
      

      【讨论】:

        【解决方案3】:

        第 1 点:将 route.js 更改为 routes.js

        第2点:我想你已经使用了

        module.exports = router;
        

        在 route.js 中

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2018-12-09
          • 1970-01-01
          • 1970-01-01
          • 2020-10-17
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-11-23
          相关资源
          最近更新 更多