0
votes

Im trying to get nodejs http to serve a vuejs application.

Vue is configured as SPA with history mode enabled. My nodejs server is set up like this:

http.createServer((req, res) => {
  fs.readFile('dist/index.html', 'utf-8', (err, content) => {
    if (err) {
      console.log('We cannot open "index.html" file.')
    }

    res.writeHead(200, {
      'Content-Type': 'text/html; charset=utf-8'
    })

    res.end(content)
  })
}).listen(port, () => {
  console.log('Server listening on: http://localhost:%s', port)
})

Taken from here: https://router.vuejs.org/guide/essentials/history-mode.html#native-node-js

This does indeed start the server and i can navigate to localhost:3000 but see a blank page.

Problem is, that with this configuration the server always returns the index.html file. Which is not wanted for static files like .js files, which results in errors.

How do i have to configure my http server so Vue will work as expected?

2

2 Answers

2
votes

You have to serve the whole dist folder, not just the index file so it can get the whole vuejs app.

You can make this easier for you by using modules like https://github.com/cloudhead/node-static

const static = require('node-static');
const http = require('http');

const distFolder = new static.Server('./dist');

http.createServer(function (req, res) {
  distFolder.serve(req, res);
}).listen(port, () => {
  console.log('Server listening on: http://localhost:%s', port)
})

With expressjs this would become

const express = require('express')
const app = express()

app.use(express.static('dist'))

app.listen(port, () => {
  console.log('Server listening on: http://localhost:%s', port)
})

EDIT:

Fallback for history mode:

http.createServer(function (req, res) {
    distFolder.serve(req, res, function (err, result) {
        // Fallback for history mode
        if (err !== null && err.status === 404) {
            distFolder.serveFile('/index.html', 200, {}, req, res);
        }
    });
}).listen(port, () => {
    console.log('Server listening on: http://localhost:%s', port)
})
0
votes

You are right, the example is a bit misleading. They say "If the URL doesn't match any static assets, it should serve the same index.html page that your app lives in." on the page but example completely ignores other static files.

You can use express - see this SO answer