首页 > 解决方案 > How to configure angular-cli proxy to solve CORS errors

问题描述

I can't figure out why my angular-cli proxy configuration is wrong. I'm still getting the CORS error from chrome.

This is the proxy configuration:

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

This is the request made by the component

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) 
      }
    )
  }

Note

  1. The proxy is working, I can see the rules applied in console
[HPM] Proxy rewrite rule created: "^/sites" ~> ""
[HPM] Subscribed to http-proxy events:  [ 'error', 'close' ]
  1. Already tried without 'pathRewrite'.

I'm still getting this CORS error, and I don't understand why, can someone help?

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.

标签: angularproxycorsangular-cli

解决方案


In your server, which is serving http://dati.venezia.it, you need to set the headers:

Access-Control-Allow-Origin: '*'

If you don't have access to the server then disable chrome web security:

in Mac OSX, use the following command to run chrome:

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

On Windows 10, Command will be:

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

推荐阅读