Angular 跨域问题解决方案
https://zhuanlan.zhihu.com/p/414843780
本地开发时,跨域问题解决:
在根目录下创建 proxy.conf.json 文件
{
"/api": {
"target": "http://localhost:3000",
"secure": false,
"logLevel": "debug",
"changeOrigin": true,
"pathRewrite": {
"^/api": ""
}
}
}
将请求 /api 的接口代理到 http://localhost:3000 下。
参数解析:
"target": "http://localhost:3000", 目标地址
"secure": false,是否需要 https
"logLevel": "debug", 只需要记录 bug 的日记
"changeOrigin": true, 是否改变请求源,如果为false 就不会请求到 target 目标地址,会使用原 host 地址
"pathRewrite": { "^/api": "" } ,将 /api 的路径替换为空字符串 "" , 因为请求的接口中并不存在 /api
然后在 angular.json 文件内的 serve 属性下添加:
"serve": {
"builder": "@angular-devkit/build-angular:dev-server",
"options": {
"browserTarget": "ng-wyy:build",
"proxyConfig": "proxy.conf.json"
},
"configurations": {
"production": {
"browserTarget": "ng-wyy:build:production"
}
}
},
重点是 "proxyConfig": "proxy.conf.json" 这句,然后重新 npm run start 即可

浙公网安备 33010602011771号