angular6 开发时请求后台的跨域问题
在项目根目录创建文件 proxy.conf.json ,配置如下:
1{
2 "/api": {
3 "target": "http://localhost:8080",
4 "secure": false,
5 "pathRewrite": {
6 "^/api": ""
7 }
8 }
9}
配置 anjular.json
找到项目根目录下的 angular.json 文件,在 projects节点->architect节点->serve节点->options节点下追加如下内容:
“proxyConfig”: “proxy.conf.json”
示例如下:
1{
2 // 省略其他代码
3 "serve": {
4 "builder": "@angular-devkit/build-angular:dev-server",
5 "options": {
6 "browserTarget": "minio-client-javascript:build",
7 "proxyConfig": "proxy.conf.json"
8 },
9 "configurations": {
10 "production": {
11 "browserTarget": "minio-client-javascript:build:production"
12 }
13 }
14 },
15 // 省略其他代码
16}
启动项目
使用方法
如果真实的URL像下面这样:
1url="http://localhost:8080/index"
2http.get(url)
使用proxy后的方法如下(这里的 api 是 proxy.conf.json 的内容开头,可自行修改):
1url="/api/index"
2http.get(url)
评论