XMLHttpRequest允许一个URL但在另一个URL上抛出NetworkError

时间:2014-07-21 18:23:38

标签: javascript google-api xmlhttprequest cross-domain

我将Google Maps API用于我正在撰写的网络应用程序,现在我遇到了跨域请求问题。有什么奇怪的是XMLHttpRequest.send()在使用"https://maps.googleapis.com/maps/api/geocode/json?address=..."时成功,但在向NetworkError发出GET请求时失败但"https://maps.googleapis.com/maps/api/directions/json?origin=...&destination=..."

以下是我使用的代码:

// HTTP GET request
function httpGetJSON(url) {
    var req = new XMLHttpRequest();
    req.open("GET", url, false);
    req.send(null);
    return JSON.parse(req.responseText);
}

// lat/lon of street address
function locationOfAddress(address) {
    var url = "https://maps.googleapis.com/maps/api/geocode/json?address=" +
        encodeURIComponent(address);
    var response = httpGetJSON(url);
    return response.results[0].geometry.location;
}

// driving distance between street addresses
function drivingDistance(addressFrom, addressTo) {
    var url = "https://maps.googleapis.com/maps/api/directions/json?origin=" +
        encodeURIComponent(addressFrom) + "&destination=" + 
        encodeURIComponent(addressTo);
    var response = httpGetJSON(url);
    return response.routes[0].legs[0].distance;
}

// getting lat/lon of White House works
var center = locationOfAddress("1600 Pennsylvania Ave NW, Washington, DC 20500");
// getting distance from White House to Capitol Building fails with NetworkError
var dist = drivingDistance(
    "1600 Pennsylvania Ave NW, Washington, DC 20500",
    "2 15th St NW, Washington, DC 20007");

两个网址之间的唯一区别是,一个网址正在访问geocode API而另一个网址使用directions API,当然查询字符串也不同。

为什么这些差异会导致一个HTTP GET请求成功而另一个失败?

(注意:我已经检查了这两个网址,并且在放入任何网络浏览器时都会获得JSON响应)

0 个答案:

没有答案