Search code examples
javascriptnode.jsvue.jsvue-clivue-cli-3

Node only sends html content to the client instead of sending a whole Vue app


I created a new vue project with the CLI and want to deploy it. Based on this documentation

https://router.vuejs.org/guide/essentials/history-mode.html#html5-history-mode

I added the history mode to the router. After running npm run build I took the example code for a static native Node server

https://router.vuejs.org/guide/essentials/history-mode.html#example-server-configurations

const http = require('http')
const fs = require('fs')
const httpPort = 3000

http.createServer((req, res) => {
  fs.readFile('../base/index.html', 'utf-8', (err, content) => {
    if (err) {
      throw err;
    }

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

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

So when navigating to localhost:3000 the vue project seems to load correctly

enter image description here

but I have a blank page with two errors

enter image description here

When I click on those js files it shows me the content of the index.html file. Obviously js is not able to understand this html content. How can I fix that problem?


Solution

  • Server will not send the whole vue app at once.

    • Browser get html file from server, when you browse to that url.
    • Browser parse the html file.
    • Browser detects assets (js, images, css).
    • Browser request those files.

    It request those file from server, but you haven't initialized server to find those files.

    So, need to add static files.

    https://expressjs.com/en/starter/static-files.html

    You can take reference from here