angular项目配置反向代理解决跨域
1. 根目录下新建proxy.conf.json文件
{ "/api/*": { "target": "http://localhost:4200", "secure": false, "changeOrigin": true, "pathRewrite": { "^/api": "" // 将请求地址中的'/api'重写为空 } } }
2. 在angular.json文件中serve下的options下面新增 "proxyConfig": "src/proxy.conf.json"
"serve": { "builder": "@angular-devkit/build-angular:dev-server", "options": { "browserTarget": "client:build", "proxyConfig": "proxy.conf.json" } }
或者在package.json里的启动命令里做如下修改:
{ "name": "client", "version": "0.0.0", "scripts": { "ng": "ng", "start": "ng serve --proxy-config proxy.conf.json" ... } }
重新启动项目,就可以实现跨域请求了!