西周舍利
2021-06-04 17:54
采纳率: 90.9%
浏览 17
已结题

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条回答 默认 最新

  • 小P聊技术 2021-06-05 09:49
    已采纳

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

     

    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"
        }
    }
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题