In my Nuxt project, I use vue2-google-maps library to create map and axios to get data from Map API. I want to get distance between 2 location in google map, so i use Directions API: https://maps.googleapis.com/maps/api/directions/json?origin=Disneyland&destination=Universal+Studios+Hollywood&key=API_KEY. When I use it with Insomnia, I retrieved data normally, like below picture:
But when i use it with nuxt using axios, I get some error like:
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.
But if i use Geocoding API with nuxt, it work normally I tried adding header Access-Control-Allow-Origin=* but still get errors. I don’t know why i get these errors. My code:
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));
Please help me. Thank you!!!
In nuxt.config.js
, you have to put credentials: false to allow CORS wildcard.
Modify config as follows.
axios: {
baseURL: 'https://maps.googleapis.com/maps/api',
proxyHeaders: false,
credentials: false
}
CORS header is not present in the response from Google Maps because it is designed to be utilized for server-side applications. For client-side (Browser), you need to make use of Official Maps library. (Shown in the above image).
Reference: https://github.com/nuxt-community/axios-module#credentials
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With