Linux+express+pm2+http-proxy-middleware构建部署Vue项目

Vue项目构建&部署


特别说明,以下操作均在服务器(centos 7)上完成,打包失败可以本地打包再上传到服务器

一 、安装Node.js

wget -O- https://raw.githubusercontent.com/aliyun-node/tnvm/master/install.sh | bash
source ~/.bashrc
tnvm ls-remote alinode 
tnvm install node-v12.5.0
# 使用需要的版本
nvm use node-v12.5.0 
node -v
npm -v

二、安装yarn、pm2

#安装yarn
npm install  -g yarn
yarn -v
# 切换npm和yarn的镜像
npm config set registry https://registry.npm.taobao.org/
yarn config set registry https://registry.npm.taobao.org/
#查看是否切换成功
npm config get registry
yarn config get registry
#安装pm2
npm install  -g pm2
pm2 -v

三、安装express,构建项目

以下步骤需切换到项目目录下进行

# 在工程下执行 yarn ,安装依赖
yarn
#编译工程
yarn build

#安装express
npm install express -g
npm install -g express-generator
express --version

# 使用express构建工程,构建完后会在当前路径下生成server文件夹
express --view=ejs  server

#将build好的dist文件夹移到server文件夹下
mv dist server/dist

# 安装http代理:
npm install --save http-proxy-middleware
# 安装connect-history-api-fallback 中间件以支持HTML5 History 模式:
npm install --save connect-history-api-fallback
# 在server目录下安装依赖
yarn install
#在serve目录下新建app.js文件

serve目录如下所示

在这里插入图片描述

四、编辑app.js文件

作用:

1、将/api/test请求代理转发到目标服务器host上,请求变为http://loacalhost:8080/test。
2、支持HTML5 History 模式

app.js

const express = require('express')
const app = express()
const proxy = require('http-proxy-middleware')
const history = require('connect-history-api-fallback')
const port = 80
const host = 'http://{{IP}}:{{PORT}}/'

app.use(history())
app.use(express.static('dist'))//build的文件

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

const proxyOption = {
  target: host,
  changeOrigin: true,
  ws: true,
  pathRewrite: {
    '^/api': ''
  },
  logLevel: 'debug'//打印日志级别
}

app.use('/api/*', proxy.createProxyMiddleware(proxyOption))

module.exports = app

在这里插入图片描述

五、运行

# 第一次运行
pm2 start app.js --name ctms --watch

pm2 status
pm2 monit

# 之后操作
pm2 start ctms
pm2 stop ctms
pm2 delete ctms

在这里插入图片描述

查看日志

pm2 logs

在这里插入图片描述

然后访问即可

在这里插入图片描述

接口调用正常

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值