- 为什么要配置代理:解决前后端的跨域问题,即前后端服务的协议/域名/端口不一致就会出现跨域现象。
如:本地的后台服务端口是3002,前台请求端口是4230 - 前台配置单一代理
1) 在项目根目录下新建一个proxy.conf.json文件
{
"/api/*": {
"target": "http://localhost:3002",
"secure": false,
"changeOrigin": true,
"logLevel": "debug",
"auth": "LOGIN:PASS"
}
}
target: 请求目标服务地址
secure:为false时,允许不是https和安全证书无效的服务
changeOrigin:为true ,允许请求跨域
2)在package.json文件中添加服务启动时同时启动代理文件
"scripts": {
"ng": "ng",
"start": "ng serve --port=4203 --open --proxy-config proxy.conf.json",
"build": "ng build --prod",
"test": "ng test",
"lint": "ng lint",
"e2e": "ng e2e"
},
若想代理多个路径,如想代理本地上传图片,可在proxy.conf.json中加一个context参数,内容是数组
{
"context":["/static","/api"],
"target": "http://localhost:3002",
"secure": false,
"changeOrigin": true,
"logLevel": "debug",
"auth": "LOGIN:PASS"
}
3)在angular.json中引用代理:
"serve": {
"builder": "@angular-devkit/build-angular:dev-server",
"options": {
"browserTarget": "iqnr-platform:build",
"proxyConfig": "proxy.config.json"
},