Serve static files, exclude 404 error on backend
/* serve.js */
const path = require("path");
const express = require("express");
const dist = path.resolve(__dirname, "..", "client", "dist");
module.exports = [
// all static files (like .js, .css, .jpg, .gif etc...)
express.static(path.resolve(dist)),
// always index.html in last stand
(req, res) => {
res.sendFile(path.resolve(dist, "index.html"));
},
];
/* index.js */
const express = require("express");
const cors = require("cors");
const morgan = require("morgan");
const app = express();
const api = require("api");
const serve = require("./serve.js");
app.use(morgan());
app.use(cors());
app.use("/api/v1/entrypoint", api);
app.use("/", serve); // <- insert after all routes and before "error handler"
app.use((err, req, res, next) => {
res.json({ success: false, message: { type: "danger", text: err.message } });
});
app.listen(9090);
Don't forget about Vue router
/* vue-router settings */
import Vue from "vue";
import VueRouter from "vue-router";
Vue.use(VueRouter);
const routes = [
{
path: "/",
name: "home",
component: () => import("@/views/Home.vue")
},
{
path: "/about",
name: "about",
component: () => import("@/views/About.vue")
},
// add 404 handler
{
path: "*",
name: "error404",
component: () => import("@/views/Error404.vue")
}
];
const router = new VueRouter({
mode: "history",
base: process.env.BASE_URL,
routes
});
export default router;