angular - 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
- 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' ]
- 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.
解决方案
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
推荐阅读
- docker - docker-compose down 不持久化 postgresql 数据
- c++ - Rectangle 类上的“Rectangle”类不存在默认构造函数
- sql - SQL - 如何克隆我的行,只更改一个字段?
- java - javah'找不到多个路径的类文件'
- javascript - CSS 未正确应用于由 JQuery 创建的元素,但在检查元素中切换元素时神奇地得到纠正
- command-line - Ping 错误 ping:-l 标志:不允许操作
- c# - Task.IsCompleted 使用缓存标志的原因是什么?
- python - 使用具有指定值集的 OneHotEncoder
- python - 将图像从一张较大的图像中分离出来
- laravel - 如何在同一个域上指向多个 laravel 项目?