Vue项目打包后部署到express服务器

Vue项目打包后部署到express服务器

Express是基于Node.js平台,快速,开放,极简的Web开发框架,如果前端需要服务器部署自己的项目,可以使用express

首先在vue项目安装 express

npm install express -save

然后根目录下新建app.js文件

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')
})

修改packge.json文件配置

添加 “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"
 },
执行 npm run start 运行服务器,打开浏览器输入 localhost:8081 便可以访问到项目

注意:如果使用vue-router的history模式,需要使用connect-history-api-fallback中间件

官方解释: 当你使用 history 模式时,URL 就像正常的 url,不过这种模式要玩好,还需要后台配置支持。因为我们的应用是个单页客户端应用,如果后台没有正确的配置,当用户在浏览器直接访问地址栏中的文件 就会返回 404,这就不好看了。
所以呢,你要在服务端增加一个覆盖所有情况的候选资源:如果 URL 匹配不到任何静态资源,则应该返回同一个 index.html 页面,这个页面就是你 app 依赖的页面。

首先安装 connect-history-api-fallback

npm install --save connect-history-api-fallback

然后在 APP.js中引入使用
const express = require('express')
const path = require('path')
const app = express()

// vue-router history模式引入connect-history-api-fallback中间件
const history = require('connect-history-api-fallback')

// 这句代码需要放在express.static上面
app.use(history())

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

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

猜你喜欢

转载自blog.csdn.net/weixin_45426836/article/details/103331052