1.本地代理
1.根目录或src目录下创建proxy.conf.json文件
2.文件中设置代理(可设置多个)
{
"/service/*": { // 匹配以/service/开头的url路径
"target": "http://localhost:3000", // 跨域时的目标地址
"pathRewrite": { // 路径重写,可选,在请求中去掉/service
"^/service": ""
},
"secure": false,//不允许非安全环境
"changeOrigin": true,//允许更改域名
}
}
3.修改命令
将package.json中的启动命令的命令改为代理
npm start/ng serve
"scripts": {
"ng": "ng",
"start": "ng serve --proxy-config proxy.conf.json",
"build": "ng build",
"watch": "ng build --watch --configuration development",
"test": "ng test",
"buildIndex": "webpack --config scripts/serverScript/webpack.index.js"
},
2.线上代理
1.根目录下创建script/index.js文件
const express = require('express');
const path = require('path');
const fs = require('fs');
const httpProxyMiddleware = require('http-proxy-middleware');//使用http-proxy-middleware
const app = new express();
const port = 8152;
const dirPath = path.join(__dirname, 'ui');
fs.readdir(dirPath, function (err, files) {
if (err) {
return console.log('error: ' + err)
}
files.forEach((file) => {
console.log(file);
})
})
app.use('/service/ui', express.static(path.join(__dirname, 'ui')))
app.use('/api', httpProxyMiddleware.createProxyMiddleware({//给需要的api配置新的代理
target: 'http://www.wanlimm.cn',//目标路径
changeOrigin: true,//允许更改域名
secure: false,//不允许非安全环境
onProxyRes: function (proxyRes, req, res) {//可添加请求头
res.header('Access-Control-Allow-Credentials', 'true');
},
}))
app.listen(port, () => console.log(`111111111 ${port}!`));
2.使用命令重新打包,部署上线
npm buildIndex