如何使用Ajax Api修复Google Distance Matrix API中的“跨源请求被阻止”[复制]

问题描述 投票:-1回答:1

我一直在尝试使用距离矩阵从谷歌请求数据,但每次我要求它使用AJAX API抛出“Cross-Origin Request Blocked”。

每当我使用PostMan时它都会正常返回。

$.ajax({
         type: "GET",
         url: "https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins=Obalende&destinations=Ikeja&mode=driving&departure_time=now&key=AIzaSyBTo0RgT_iA87Hd76gX8zYixB3PZh3z454",
         dataType: "json",
         crossDomain: true,
         cache: false,
         success: function(data){
         console.log(data);
  }
})

这是返回的错误:

跨源请求已阻止:同源策略禁止在https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins=Obalende&destinations=Ikeja&mode=driving&departure_time=now&key=AIzaSyBTo0RgT_iA87Hd76gX8zYixB3PZh3z454&_=1555970031620上读取远程资源。 (原因:缺少CORS标题'Access-Control-Allow-Origin')。

jquery ajax google-api cors google-distancematrix-api
1个回答
0
投票

要解决此问题,请托管一个简单的http服务器,然后从那里点击您的页面,而不是从本地文件运行。

在终端中使用以下命令,而在工作目录中,对于Windows,请参阅此链接microsoft simple http server

http-server -p 4090 .

将允许您进入浏览器并输入地址http://localhost:4090,使用这个简单的http服务器时不应该发生错误。如果您在页面中使用php并需要提供这些页面使用

php -S 127.0.0.1:4090

或者,在Safari中,启用“开发人员”菜单,然后在其中单击以下选项

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.