vue 项目通过 build 打包结束后,会生成 dist 目录,此时可能需要发布前在本地进行预览
vue-cli部署中讲如何讲 dist 目录在本地进行预览
npm install -g serve
# -s 参数的意思是将其架设在 Single-Page Application 模式下
# 这个模式会处理即将提到的路由问题
serve -s dist
但此时预览是访问不到后台接口的,你可能会想:我在配置文件中已经配置了 devServer,为什么还会跨域呢?
devServer: {
// 次代理仅针对本地开发服务(npm run serve)
proxy: {
'/boss': {
target: 'http://eduboss.lagou.com',
changeOrigin: true // 把请求头中的 host 配置为 target
},
'/front': {
target: 'http://edufront.lagou.com',
changeOrigin: true
}
}
}
这里的 devServer 主要针对开发环境的接口代理,一旦项目打包部署后,就无法在生效,此时需要解决跨域问题,这里我们就可以通过 nodeJS 实现
在当前项目下安装 express npm install -D express 为开发依赖,创建 test-serve/app.js 文件
使用http-proxy-middleware中间件实现接口跨域
// app.js
const express = require('express')
const app = express()
const path = require('path')
const { createProxyMiddleware } = require('http-proxy-middleware')
// 托管了 dist 目录,当访问 / 的时候,默认会返回托管目录中的 index.html 文件
app.use(express.static(path.join(__dirname, '../dist')))
app.use(
'/boss',
createProxyMiddleware({
target: 'http://eduboss.lagou.com',
changeOrigin: true,
})
)
app.use(
'/front',
createProxyMiddleware({
target: 'http://edufront.lagou.com',
changeOrigin: true,
})
)
app.listen(3000, () => {
console.log('running...')
})
通过 node test-serve/app.js 启动,访问 http://localhost:3000 实现跨域处理
接着将命令添加到 package.json 的 scripts 中
"scripts": {
"serve": "vue-cli-service serve",
"build": "vue-cli-service build",
"lint": "vue-cli-service lint",
"preview": "node test-serve/app.js"
},
网友评论