簡體   English   中英

如何配置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的服務器中,您需要設置標題:

Access-Control-Allow-Origin: '*'

如果您無權訪問服務器,請禁用Chrome Web安全性:

在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

在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