Angular 解决跨域 配置代理 (适用于Angular2+)

1. 新建proxy.conf.json 文件 内容如下:

{
     "/api": {
         "target": "http://124.77.3.162:8888",
         "secure": false,
         "router" : {
         "/v1/index": "http://125.78.3.162:8888",
         "/v1/finances": "http://124.77.3.162:8888"
     }
    }
}
上面代码最终访问结果:http://124.77.3.162:8888/api/v1/finances

2. 在package.json文件中引入代理文件  修改scriptsstart

{
"name": "yqfx",
"version": "0.0.0",
"license": "MIT",
"angular-cli": {},
"scripts": {
"ng": "ng",
"start": "ng serve --sourcemap=false--host 0.0.0.0 --proxy-config proxy.conf.json",
"test": "ng test",
"pree2e": "webdriver-manager update --standalone false --gecko false",
"e2e": "protractor"
},
"private": true,
"dependencies": {
"@angular/common": "^2.3.1",
"@angular/compiler": "^2.3.1",
"@angular/core": "^2.3.1",
"@angular/forms": "^2.3.1",
"@angular/http": "^2.3.1",
"@angular/platform-browser": "^2.3.1",
"@angular/platform-browser-dynamic": "^2.3.1",
"@angular/router": "^3.3.1",
"core-js": "^2.4.1",
"echarts-ng2": "^1.4.1",
"primeng": "1.1.4",
"rxjs": "^5.0.1",
"ts-helpers": "^1.1.1",
"zone.js": "^0.7.2"
},
"devDependencies": {
"@angular/compiler-cli": "^2.3.1",
"@types/echarts": "0.0.9",
"@types/jasmine": "2.5.38",
"@types/node": "^6.0.42",
"angular-cli": "1.0.0-beta.28.3",
"codelyzer": "~2.0.0-beta.1",
"jasmine-core": "2.5.2",
"jasmine-spec-reporter": "2.5.0",
"karma": "1.2.0",
"karma-chrome-launcher": "^2.0.0",
"karma-cli": "^1.0.1",
"karma-jasmine": "^1.0.2",
"karma-remap-istanbul": "^0.2.1",
"protractor": "~4.0.13",
"ts-node": "1.2.1",
"tslint": "^4.3.0",
"typescript": "~2.0.3"
}
}

3. 在service中地址写法如下,就能匹配到 http://124.77.3.162:8888/api/v1/finances

getConditionList( id): Promise< any> {

let headers = new Headers({
'Content-Type' : 'application/json'
});
return this. http
. get( "/api/v1/finances/getCondition", { headers: headers })
. toPromise()
. then( response => {
return response. json() as any;
})
. catch( this. handleError);
}


你可能感兴趣的:(Angular 解决跨域 配置代理 (适用于Angular2+))