一 安装serve
npm i serve -g
打包
npm run build
serve -S dist
- 此时发现请求跨越,所以用第二种引入中间件http-proxy-middleware(用于把请求代理转发到其他服务器的中间件)方法来本地预览
二 http-proxy-middleware
-
npm install --save-dev http-proxy-middleware
image.png
//test-serve/app.js
const express = require('express');
const { createProxyMiddleware } = require('http-proxy-middleware');
const app = express();
const path = require('path');
// 托管了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);
对应的vue.config.js里面配置如下
devServer: {
proxy: {
'/boss': {
target: 'http://eduboss.lagou.com',
changeOrigin: true// 把请求头中的 host 配置为 target
},
'/front': {
target: 'http://edufront.lagou.com',
changeOrigin: true // 把请求头中的 host 配置为 target
}
}
}
直接npm run preview
访问localhost:3000就可以看到了
网友评论