简体   繁体   English

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

[英]How to configure angular-cli proxy to solve CORS errors

I can't figure out why my angular-cli proxy configuration is wrong. 我不知道为什么我的angular-cli代理配置错误。 I'm still getting the CORS error from chrome. 我仍然从Chrome收到CORS错误。

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'. 已经尝试不使用“ pathRewrite”。

I'm still getting this CORS error, and I don't understand why, can someone help? 我仍然收到此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.

In your server, which is serving http://dati.venezia.it , you need to set the headers: 在提供http://dati.venezia.it的服务器中,您需要设置标题:

Access-Control-Allow-Origin: '*'

If you don't have access to the server then disable chrome web security: 如果您无权访问服务器,请禁用Chrome Web安全性:

in Mac OSX, use the following command to run chrome: 在Mac OSX中,使用以下命令运行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: 在Windows 10上,命令为:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM