版本:

angular cli 反向代理实现跨域-LMLPHP

1、后端实现跨域(php)

header("Access-Control-Allow-Origin: *");
// // 响应类型
// header('Access-Control-Allow-Methods:POST');
// // 响应头设置
// header('Access-Control-Allow-Headers:x-requested-with, content-type');

2、前端跨域

项目目录下新建proxy.config.json文件

angular cli 反向代理实现跨域-LMLPHP

proxy.config.json

{
"/api": {
"target": "http://localhost", // php服务路径
"logLevel": "debug",
"changeOrigin": true,
"pathRewrite": {
"^/api": ""
}
}
}

package.json

{
"name": "web",
"version": "0.0.0",
"scripts": {
"ng": "ng",
"start": "ng serve --proxy-config proxy.config.json --open", // 修改
"build": "ng build",
"test": "ng test",
"lint": "ng lint",
"e2e": "ng e2e"
},
"private": true,
"dependencies": {
"@angular/animations": "^8.0.0",
"@angular/cdk": "^8.0.0",
"@angular/common": "~8.0.0",
"@angular/compiler": "~8.0.0",
"@angular/core": "~8.0.0",
"@angular/forms": "~8.0.0",
"@angular/material": "^8.0.0",
"@angular/platform-browser": "~8.0.0",
"@angular/platform-browser-dynamic": "~8.0.0",
"@angular/router": "~8.0.0",
"@types/echarts": "^4.4.1",
"@types/jquery": "^3.3.29",
"chart.js": "^2.8.0",
"crypto": "^1.0.1",
"echarts": "^4.4.0",
"express": "^4.17.1",
"font-awesome": "^4.7.0",
"jquery": "^3.4.1",
"mysql": "^2.17.1",
"ngx-echarts": "^4.2.1",
"primeflex": "^1.0.0",
"primeicons": "^1.0.0",
"primeng": "^7.1.3",
"rxjs": "~6.4.0",
"tslib": "^1.9.0",
"zone.js": "~0.9.1"
},
"devDependencies": {
"@angular-devkit/build-angular": "~0.800.0",
"@angular/cli": "~8.0.1",
"@angular/compiler-cli": "~8.0.0",
"@angular/language-service": "~8.0.0",
"@types/jasmine": "^3.3.16",
"@types/jasminewd2": "~2.0.3",
"@types/node": "^8.10.59",
"codelyzer": "^5.0.0",
"jasmine-core": "~3.4.0",
"jasmine-spec-reporter": "~4.2.1",
"karma": "~4.1.0",
"karma-chrome-launcher": "~2.2.0",
"karma-coverage-istanbul-reporter": "~2.0.1",
"karma-jasmine": "~2.0.1",
"karma-jasmine-html-reporter": "^1.4.0",
"node-mysql": "^0.4.2",
"protractor": "~5.4.0",
"ts-node": "~7.0.0",
"tslint": "~5.15.0",
"typescript": "~3.4.3"
}
}

启动使用 npm start

访问使用 http:localhost:4200/api  就会映射到http:localhost

this.http.post('http://localhost:4200/api', {name: this.name, company: this.company, price: this.price }, {
headers: {
'Content-Type': 'application/json'
}
}).subscribe((res: any) => {
if (res.resultCode == 200) { }
// 加载成功之后做一些事
}, (err: any) => {
});
05-26 23:30