2

I created a VueJs page with the CLI. I would like to show it to other people without having the Vue CLI or Node installed. Just like you normally open .html files in your browser I would like to open the index.html file after building it.

When I open the file I get an empty page with 404 error messages in the console. I took these docs

https://cli.vuejs.org/guide/deployment.html#general-guidelines

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

and added mode: "history", to my router object. After building the project with the Vue CLI I setup a simple Node server

const http = require('http');
const server = http.createServer();
const fs = require('fs');
const port = 3000;

server.on('request', async (req, res) => {
  const htmlContent = fs.readFileSync('./index.html', 'utf-8');

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

  res.end(htmlContent);
});

server.listen(port, err => {
  console.log(`server is listening on ${port}`)
})

When running the server I call http://localhost:3000/ and get an empty page with two errors

enter image description here

What am I missing?

2 Answers 2

1

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 you 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;
var hostname = '127.0.0.1';

app.listen(port, hostname, () => {
   console.log(`Server running at http://${hostname}:${port}/`);
 });

after that you could run :

 node server

and your project will be served at the given host and port

Assuming that you have already the dist directory, if you don't have it run :

npm run build

in order to generate it

Sign up to request clarification or add additional context in comments.

1 Comment

well I really don't know why this is working and my Node script doesn't but well I'll use this one then :)
1

I'd try this from your project root.

npm install -g serve
serve -s dist

If you get the same issue with this maybe you've changed some default configuration in your vue.json.

Your code isn't working, as far as I can tell, because you're serving every http request index.html (which is why you see <, which is likely the <DOCTYPE...>. serve is a much safer, well thought out approach if you want to build it locally and take a look.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.