Skip to content

Instantly share code, notes, and snippets.

@tomasevich
Last active February 28, 2020 08:16
Show Gist options
  • Save tomasevich/55614f0f0970fe715feba1cfcb978008 to your computer and use it in GitHub Desktop.
Save tomasevich/55614f0f0970fe715feba1cfcb978008 to your computer and use it in GitHub Desktop.

VueJS + ExpressJS

Serve static files, exclude 404 error on backend

Make middleware

/* 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"));
  },
];

Require middleware

/* 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);

Frontend routing

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;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment