ExpressJS服务器在页面刷新上返回404错误

时间:2020-07-17 12:40:47

标签: javascript node.js express vue.js

我有一个Express JS服务器,在其上面添加了Vue CLI单页应用程序。 Vue还带有Vue路由器。

问题:

问题是刷新时每个页面/路径上都出现404错误。

文件:

Vue路由器:

import Vue from "vue";
import VueRouter from "vue-router";
import Home from "../views/Home.vue";

Vue.use(VueRouter);

const routes = [
  {
    path: "/",
    redirect: '/home',
    component: Home,
  },
  {
    path: "/home",
    name: "Home",
    component: Home,
  },
  {
    path: "/dhcpIP",
    name: "DHCP",
    component: () => import(/* webpackChunkName: "dhcpIP" */ "../views/DHCP.vue")
  },
  {
    path: "/staticIP",
    name: "Static",
    component: () => import(/* webpackChunkName: "staticIP" */ "../views/Static.vue")
  },
  {
    path: "/files",
    name: "FileManager",
    component: () => import(/* webpackChunkName: "files" */ "../views/FileManager.vue")
  },
  {
    path: "/update",
    name: "Update",
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () => import (/* webpackChunkName: "update" */ "../views/Update.vue")
  },
];

const router = new VueRouter({
  mode: "history",
  routes,
});

export default router;

如您所见,我没有任何子页面。

ExpressJS服务器文件:

const express = require("express");
const history = require('connect-history-api-fallback');
const path = require("path");

require("dotenv").config();

const debug = require("debug")("poi:server");
const favicon = require("serve-favicon");
// generating logs
const logger = require("morgan");
const bodyParser = require("body-parser");
const http = require("http");

const { exec } = require("child_process");

const app = express();

app.use(favicon(path.join(__dirname, "../dist/favicon.ico")));

app.use(logger("dev"));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header(
    "Access-Control-Allow-Headers",
    "Origin, X-Requested-With, Content-Type, Accept"
  );
  next();
});

// serve the Vue Interface
app.use(express.static(path.join(__dirname, "../dist")));
app.use(history({
  disableDotRule: true,
  verbose: true
}));

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  console.dir(req);
  console.dir(res);
  let err = new Error("Not Found");
  err.status = 404;
  next(err);
});

// error handler
app.use(function(err, req, res /*next*/) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get("env") === "development" ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render("error");
});

/**
 * Event listener for HTTP/S server "error" event.
 */

function onError(error) {
  if (error.syscall !== "listen") {
    throw error;
  }
  let port = this.address().port;
  //   let port = http_port;
  let bind = typeof port === "string" ? "Pipe " + port : "Port " + port;

  // handle specific listen errors with friendly messages
  switch (error.code) {
    case "EACCES":
      console.error(bind + " requires elevated privileges");
      process.exit(1);
      break;
    case "EADDRINUSE":
      console.error(bind + " is already in use");
      process.exit(1);
      break;
    default:
      throw error;
  }
}

/**
 * Event listener for HTTP/S server "listening" event.
 */

function onListening() {
  let addr = this.address();
  let bind = typeof addr === "string" ? "pipe " + addr : "port " + addr.port;
  debug("Listening on " + bind);
}

// Creating the HTTP server

const http_port = process.env.HTTP_PORT;
const http_server = http.createServer(app);

http_server.listen(http_port);
console.log(http_port);

http_server.on("error", onError);
http_server.on("listening", onListening);

console.log(`Server started on http://localhost:8080`);

尝试的解决方案:

我尝试使用connect-history-api-fallback来修复它,但是没有解决。

我接下来尝试的是this解决方案。
使用此方法时,我可以在任何页面/路径上刷新,但是我的POST方法不起作用,尝试进行POST时得到以下行:

Not rewriting POST /home because the method is not GET

我有一个简单的测试POST方法:

app.post("/home", function(req, res) {
  let foo = req.body.command;

  console.log("req.body: ");
  console.log(foo);

  res.send("Hello !");
}

“你好!”永不发送。相反,我将整个index.html作为字符串发送。可能来自:

res.sendFile(`${buildLocation}/index.html`);

您怎么看?如何解决由于刷新页面而导致的404问题,又如何保持POST方法的功能。

0 个答案:

没有答案