Cross-Origin 使用 axios 和 Nuxt js 从 Directions API 获取数据时读取阻塞 (CORB)

Cross-Origin Read Blocking (CORB) when get data from Directions API using axios with Nuxt js

在我的 Nuxt 项目中,我使用 vue2-google-maps 库创建 map 和 axios 从 Map API 获取数据。 我想获得 google 地图中 2 个位置之间的距离,所以我使用方向 API:https://maps.googleapis.com/maps/api/directions/json?origin=Disneyland&destination=Universal+Studios+Hollywood&key=API_KEY。 当我使用 Insomnia 时,我可以正常检索数据,如下图所示:

但是当我使用 axios 将它与 nuxt 一起使用时,我得到一些错误,如:

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.

Cross-Origin Read Blocking (CORB) blocked cross-origin response https://maps.googleapis.com/maps/api/directions/json?origin=Disneyland&destination=Universal+Studios+Hollywood&key=API_KEY with MIME type application/json. See https://www.chromestatus.com/feature/5629709824032768 for more details.

但是如果我在 nuxt 中使用 Geocoding API,它可以正常工作 我尝试添加 header Access-Control-Allow-Origin=* 但仍然出现错误。 我不知道为什么会出现这些错误。 我的代码:

axios
  .get('https://maps.googleapis.com/maps/api/directions/json?origin=Disneyland&destination=Universal+Studios+Hollywood&key=API_KEY')
  .then(res => {
      console.log("Res: ");
      console.log(res)
   })
   .catch(err => console.log(err));

请帮助我。 谢谢!!!

nuxt.config.js 中,您必须输入 credentials: false 以允许 CORS 通配符。

修改配置如下。

axios: {
   baseURL: 'https://maps.googleapis.com/maps/api',
   proxyHeaders: false,
   credentials: false
}

CORS header 不存在于 Google 地图的响应中,因为它旨在用于 server-side 应用程序。对于 client-side(浏览器),您需要使用 Official Maps library。 (如上图所示)。

参考:https://github.com/nuxt-community/axios-module#credentials