如何将Vue Express和Node SPA部署到Heroku,以便加载Vue路由器组件?

时间:2020-08-31 23:25:59

标签: node.js vue.js vue-router vue-cli heroku-cli

我正在尝试部署VueJS Node全栈应用程序。当我在本地运行该应用程序时,该应用程序即可运行,但是当我将其部署到Heroku时,仅会加载“ /”页面。其余路由会显示404 Not Found消息。以下是我的Vue Router和Express文件。

React Rounter:

import Vue from "vue";
import VueRouter from "vue-router";
import Home from "../components/Home.vue";
import { uriBase } from "../const";
import Services from "../components/Services.vue";
import MeetBrett from "../components/Brett.vue";



Vue.use(VueRouter);

const routes = [
  {
    path: "/",
    name: "home",
    component: Home
  },
  {
    path: "/Services",
    name: "Services",
  
    // 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: Services
  },
  {
    path: "/meetBrett",
    name: "MeetBrett",
    // 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: MeetBrett
  },
  {
    path: "/quote",
    name: "Get Quote",
    component: () =>
      import(/* webpackChunkName: "about" */ "../components/GetQuotePage.vue")
  }
];

const router = new VueRouter({
   // base: '/dev', // for dev
  mode: "history",
  base: uriBase,
  routes
 

});

export default router;

具有Express的节点,我使用connect-history-api-fallback

const express = require ("express");
const app = express();
const cors = require("cors");
const bodyParser = require("body-Parser");
const serveStatic = require("serve-static");
const path = require('path');
const history = require('connect-history-api-fallback');

require('dotenv').config("./process.env")

const port = process.env.PORT || 5000;

app.set(port)

const staticFileMiddleware = express.static(path.join(__dirname + "/public"));

app.use(express.json());
app.use(cors());
app.use(bodyParser());

// app.use(serveStatic(path.join(__dirname, '/public')));
// app.use(/.*/, (req, res) => express.static(path.join(__dirname, "/public")));
app.use(
  history({
    verbose: true,
    index: 'index.html'
  })
);

app.use(staticFileMiddleware);


app.listen(port, () => console.log(`Listening on port ${port}`));

1 个答案:

答案 0 :(得分:0)

使用connect-history-api-fallback中间件的正确方法是指定要重写的绝对路径。因此,如果您有index: 'index.html',应该是index: '/index.html'

尽管这是default,所以您应该避免覆盖它。

app.use(history({
  verbose: true
}));
app.use(staticFileMiddleware);

一些额外的东西供您尝试...

vue.config.js文件中设置前端应用程序的基本路径

module.exports = {
  publicPath: process.env.NODE_ENV === 'production'
    ? '/'
    : '/dev/'
}

并在您的路由器中引用

const router = new VueRouter({
  mode: "history",
  base: process.env.BASE_URL,
  routes
});