欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

angular cli 反向代理实现跨域

程序员文章站 2022-06-07 11:28:20
版本: 1、后端实现跨域(php) header("Access-Control-Allow-Origin: *"); // // 响应类型 // header('Access-Control-Allow-Methods:POST'); // // 响应头设置 // header('Access-C ......

版本:

angular cli 反向代理实现跨域

 

 

 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 反向代理实现跨域

 

 

 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) => {
      });