2
votes

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?

2

2 Answers

3
votes

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

3
votes

as @Sukul answer before, you just need to server the static files because you have now only one handler to server all the request coming with the HTML file (the mount point document) and when its requesting the *.js app it's expecting the valid javascript syntax instead it finds HTML, and that what the error messages are on the network tab

const http = require('http')
const fs = require('fs')
const nStatic = require('node-static');
var fileServer = new nStatic.Server('./public');

const httpPort = 3000

const controllers = (req,res)=>{
  if(req.url.includes(".")
   return fileServer.serve(req, res);
  else
  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)
  })
}
}

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

node-static ref

however, I highly recommend you trying to use express.js