javascript - Cross-Origin blocking AJAX connection with Google Maps even with the headers seted
问题描述
Well, I have a SSL domain calling for the Google Maps API.
function typed_address(str) {
var url = 'https://maps.google.com/maps/api/geocode/json?address='+str;
var xhttp = new XMLHttpRequest();
xhttp.open('GET', url, false);
xhttp.setRequestHeader('Access-Control-Allow-Origin','*');
xhttp.setRequestHeader('Access-Control-Allow-Credentials', 'true');
xhttp.setRequestHeader('Access-Control-Allow-Methods', 'GET, OPTIONS');
xhttp.setRequestHeader('Access-Control-Allow-Headers', 'Content-Type');
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var result = JSON.parse(this.response);
if (result.results[0]) {
latlng = result.results[0].geometry.location;
document.cookie = 'lat=' + latlng.lat;
document.cookie = 'lng=' + latlng.lng;
map.setCenter(latlng);
marker.setPosition(latlng);
}
}
};
xhttp.send();
}
When I do this request within my SSL domain, I have this on my browser console:
Blocked cross-origin request: Same Origin Policy prevents the remote resource from reading at https://maps.google.com/maps/api/geocode/json?address=R.%20PROF.%20LOURIVAL 20% 20% 20% 20% 20% 20% 20% 20PE% 2055016-445. (Reason: 'access-control-allow-credentials' symbol missing in CORS 'Access-Control-Allow-Headers' header during CORS pre-connection
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://maps.google.com/maps/api/geocode/json?address=R.%20PROF.%20LOURIVAL%20VILANOVA%20-%20UNIVERSIT % 20% 20%, 20% 20% 20%, 2055016-445. (Reason: CORS request did not succeed).
NetworkError: A network error occurred.
And here below is what I get on Network debug:
Does anybody know what I'm doing wrong? It seems that it's not reading my request headers...
解决方案
当网页输出到浏览器时,您需要指定标题。不在ajax请求中。如果您使用 php,您可以添加 sheaders
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Max-Age: 1000");
header("Access-Control-Allow-Headers: X-Requested-With, Content-Type, Origin, Cache-Control, Pragma, Authorization, Accept, Accept-Encoding");
header("Access-Control-Allow-Methods: PUT, POST, GET, OPTIONS, DELETE");
要在 Ruby 中设置标题,请参阅这篇文章
推荐阅读
- c# - Asp.Net Core 2 - 从和到数据库的音频文件
- asp.net - Understanding App Insights end to end for occassional long response times
- android - What version number should I use for minimum in ActionCodeSettings.Builder.setAndroidPackageName()?
- mysql - Laravel relationships in CRUD application
- java - 将会话超时设置为仅在用户处于非活动状态时刷新页面并在用户处于活动状态时将其重置?
- c++ - 更新纹理的问题
- c# - NET Core 2 MVC - Storing objects for GET method
- sql - Group By 子句中的别名 - 标识符无效
- javascript - 在图像中显示二值图像数据
- angular - 在使用 angular 5 httpclient 时,从 response.json() 更改为仅响应会引发编译错误