Express is a fast, open and minimalist Web development framework based on node. js platform. If the front end needs the server to deploy its own project, you can use Express

Start by installing Express in the VUE project

npm install express -save

Then create the app.js file in the root directory

const express = require('express')
const path = require('path')
const app = express()
app.use(express.static(path.join(__dirname, 'dist')))
app.listen(8081.() = > {
  console.log('app listening on port 8081')})Copy the code

Modify the packge.json file configuration

Add “start”: “node app.js”

"scripts": {
  "serve": "vue-cli-service serve --open"."build": "vue-cli-service build"."lint": "vue-cli-service lint"."start": "node app.js"
 },
Copy the code
Run NPM run start to run the server, open a browser and type localhost:8081 to access the project

Note: If vue-Router history mode is used, the connect-history-apI-Fallback middleware is required

Official explanation: When you use History mode, the URL is just like a normal URL, but this mode needs to be configured in the background to play well. Because our application is a single-page client application, if the background is not properly configured, when the user accesses the file in the address bar directly in the browser, it will return 404, which is not pretty. So, you add a candidate resource on the server that covers all cases: if the URL doesn’t match any static resource, it should return the same index.html page that your app relies on.

First, install connect-history-apI-fallback

npm install –save connect-history-api-fallback

Then use it in app.js
const express = require('express')
const path = require('path')
const app = express()

// Vue-router history introduces connect-history-api-fallback middleware
const history = require('connect-history-api-fallback')

// This code needs to be placed on express.static
app.use(history())

app.use(express.static(path.join(__dirname, 'dist')))

app.listen(8081.() = > {
  console.log('app listening on port 8081')})Copy the code