[Vuejs]-Vue js deploying in production seems harder then it is

0👍

I was struggling with the same issue. The problem was that when the browser requests the javascript and css files, the contents of the index file is sent instead.

Solved it by following step 3 of this tutorial.

Since Vue is only a frontend library, the easiest way to host it and
do things like serve up assets is to create a simple Express friendly
script that Heroku can use to start a mini-web server. Read up quickly
on Express if you haven’t already. After that, add express:

npm install express --save

Now add a server.js file to your project’s root directory:

// server.js

var express = require('express');
var path = require('path');
var serveStatic = require('serve-static');

app = express();
app.use(serveStatic(__dirname + "/dist"));

var port = process.env.PORT || 5000;
app.listen(port);

console.log('server started '+ port);

After that, since the idea is to serve index.html in the first place, I borrowed this idea and added the following to my code (notice I used sendFile if the request is html):

app.use((req, res, next) => {
    res.status(404)

    if (req.accepts("html")) {
        res.sendFile(path.join(__dirname + "/dist/index.html"))
        return
    }

    if (req.accepts("json")) {
        res.send({error: "Not found"})
        return
    }

    res.type("txt").send("Not found")
})

0👍

A little bit late, but I have used this to sendFile index.html up on 404 response.

app.use((err, req, res, next) => {
console.error(err.stack);
res.status(404).sendFile(path.resolve(__dirname, "dist", "index.html"));
})

Explanation:
err will be defined when the request is erroneous. res.status will set the status to 404 code and the app will sendFile the resolved index.html. (Notice that I used __dirname and path.resolve together to build an absolute path to be safe.

Leave a comment