如何配置angular-cli代理解决CORS错误

How to configure angular-cli proxy to solve CORS errors

我不明白为什么我的 angular-cli 代理配置是错误的。 我仍然收到来自 chrome 的 CORS 错误。

这是代理配置:

 "/sites": {
        "target": "http://dati.venezia.it",
        "secure": false,
        "logLevel": "debug",
        "changeOrigin": true,
        "pathRewrite": {
            "^/sites": ""
        }
    }

这是组件提出的请求

ngOnInit() {
    this.getData()
  }

  getBaseUrl() {
    return 'http://dati.venezia.it/';
  }

  getData(){
    const headers = new HttpHeaders({ 'Content-Type': 'text/plain' });
    this.http.get(this.getBaseUrl() + 'sites/default/files/dataset/opendata/temparia.json', { responseType: 'text', headers }).subscribe(
      data => {
        console.log('getData OK -> ', data);

      },
      error => { 
        console.log('getData ERROR -> ', error) 
      }
    )
  }

备注

  1. 代理正在运行,我可以在控制台中看到应用的规则
[HPM] Proxy rewrite rule created: "^/sites" ~> ""
[HPM] Subscribed to http-proxy events:  [ 'error', 'close' ]
  1. 已经尝试过 'pathRewrite'。

我仍然收到此 CORS 错误,我不明白为什么,有人可以帮忙吗?

Access to XMLHttpRequest at 'http://dati.venezia.it/sites/default/files/dataset/opendata/temparia.json' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

在服务于 http://dati.venezia.it 的服务器中,您需要设置 headers:

Access-Control-Allow-Origin: '*'

如果您无法访问服务器,请禁用 chrome 网络安全:

在MacOSX中,使用如下命令运行chrome:

open -n -a /Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --args --user-data-dir="/tmp/chrome_dev_test" --disable-web-security

在 Windows 10,命令将是:

C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --disable-web-security --disable-gpu --user-data-dir=~/chromeTemp