【问题标题】:Express root route not working in productionExpress 根路由在生产中不起作用
【发布时间】:2019-07-19 17:55:51
【问题描述】:

我创建了一个简单的 Node 应用程序,其中包含 5 条服务于不同 HTML 文档的路由。在 localhost 上运行时,所有路由都正常工作,但是当我在生产环境中运行应用程序时,我的根路由正在提供 404 页面,这意味着该路由不存在。

我已按照their guide 中的说明设置了 A2 托管。你可以test the app here

我想问题是我从指南中复制的 .htaccess 文件,但我不明白其中的一行。这是位于 public_html 文件夹中的代码:

app.js

const path = require("path");

const express = require("express");
const bodyParser = require("body-parser");

const appRoutes = require("./routes/app");
const errorController = require("./controllers/error");

const app = express();
app.set("view engine", "ejs");

app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, "public")));

app.use(appRoutes);
app.use(errorController.get404);

app.listen(40000, () => console.log("Server is up on port 40000!"));

routes/app.js

const express = require("express");

const appController = require("../controllers/app");

const router = express.Router();

router.get("/", appController.getIndex);
router.get("/work", appController.getWork);
router.get("/services", appController.getServices);
router.get("/blog", appController.getBlog);
router.get("/contact", appController.getContact);

module.exports = router;

controllers/app.js

exports.getIndex = (req, res, next) => {
  res.render("index");
};

exports.getWork = (req, res, next) => {
  res.render("work");
};

exports.getServices = (req, res, next) => {
  res.render("services");
};

exports.getBlog = (req, res, next) => {
  res.render("blog");
};

exports.getContact = (req, res, next) => {
  res.render("contact");
};

控制器/error.js

exports.get404 = (req, res, next) => {
  res.status(404).render("404");
};

.htaccess

RewriteEngine On
RewriteRule ^$ http://127.0.0.1:40000/ [P,L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ http://127.0.0.1:40000/$1 [P,L]

【问题讨论】:

  • 我已经设置了请求日志中间件,似乎应用程序正在向 /index.php 发出 GET 请求,而不是 /。其他 GET 请求运行良好。我在public_html 中没有index.php 文件,因为它是一个Node 应用程序。这有帮助吗?

标签: javascript node.js .htaccess express routing


【解决方案1】:

由于您可以联系到your home page by port 40000,因此问题肯定出在 .htaccess 文件中。

您可以尝试在最后一条规则中添加斜线吗?

RewriteRule ^/(.*)$ http://127.0.0.1:40000/$1 [P,L]

或在此之前添加

RewriteBase /

【讨论】:

  • 我添加了一个斜杠并修复了主页,但现在我在其他路由上收到以下错误:在此服务器上找不到请求的 URL /work。添加 RewriteBase 似乎完全没有效果。
  • 我已经设置了请求日志中间件,似乎该应用正在向/index.php 而不是/ 发出GET 请求。其他 GET 请求运行良好。我在public_html 中没有index.php 文件,因为它是一个Node 应用程序。这有帮助吗?
【解决方案2】:

.htaccess 文件是问题所在,在顶部添加此文件后它现在可以工作了:

DirectoryIndex disabled

感谢您的帮助!

【讨论】:

    猜你喜欢
    • 2019-06-08
    • 2015-12-06
    • 1970-01-01
    • 1970-01-01
    • 2017-04-17
    • 1970-01-01
    • 2020-09-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多