angular启动项目,前端跨域问题怎么解决

import { Component, OnInit } from '@angular/core';
import * as echarts from 'echarts';
import 'echarts-gl';
import * as $ from 'jquery';

@Component({
  selector: 'app-echarts-glreal',
  templateUrl: './echarts-glreal.component.html',
  styleUrls: ['./echarts-glreal.component.scss']
})
export class EchartsGLRealComponent implements OnInit {

  ROOT_PATH = 'https://echarts.apache.org/examples';

  constructor() { }

  ngOnInit(): void {
    this.initChart();
  }

  initChart() {

    const ec = echarts as any;

    const echartReal3D = ec.init(document.getElementById('echartReal3D'));

    $.get(this.ROOT_PATH +'data/asset/data/life-expectancy-table.json', function (data) {
      echartReal3D.setOption({
        grid3D: {},
        xAxis3D: {},
        yAxis3D: {},
        zAxis3D: {},
        dataset: {
          source: data
        },
        series: [
          {
            type: 'scatter3D',
            symbolSize: 2.5
          }
        ]
      })
    });

  }
}
Access to XMLHttpRequest at 'https://echarts.apache.org/examples/data/asset/data/life-expectancy-table.json' from origin 'http://localhost:4200' has been blocked by CORS policy: The 'Access-Control-Allow-Origin' header has a value 'https://echarts.apache.org' that is not equal to the supplied origin.
echarts.apache.org/examples/data/asset/data/life-expectancy-table.json:1
Failed to load resource: net::ERR_FAILED

 

在进行项目开发过程中,经常会遇到跨域问题,下面就通过一些配置进行解决跨域问题。

 

1.在项目根目录下进行创建文件 proxy.config.json;

{
    "/": {
        "target": "", //要指向的域名或端口号
        "logLevel": "debug", //
        "secure": false, //
        "changeOrigin": true, //
        "pathRewrite": {
            "^/": ""
        }
    }
}

2. 修改启动文件:

修改angular.json的配置文件:

{
      "projects": {
        "my-app": {
          "architect": {
            "serve": {
              "builder": "@angular-devkit/build-angular:dev-server",
              "options": {
                "browserTarget": "my-app:build",
                "proxyConfig": "proxy.config.json"
              },
              "configurations": {
                "production": {
                  "browserTarget": "my-app:build:production"
                }
              }
            }
          }
        }
      }
    }
}

不修改angula.json文件,修改package.json文件的start命令;

{
    "name": "my-app",
    "version": "0.0.0",
    "scripts": {
        "ng": "ng",
        "start": "ng serve --proxy-config proxy.config.json",
        "build": "ng build",
        "test": "ng test",
        "lint": "ng lint",
        "e2e": "ng e2e"
    }
}