Search code examples
javascriptgoogle-cloud-platformhttprequestgoogle-directions-api

Fetch has been blocked by CORS policy in JavaScript (Google Cloud Platform)


I have encountered a problem regarding a http request to Google Platform API. This is the example https: https://maps.googleapis.com/maps/api/directions/json?key={my api key}&origin=And%C4%9Bl&destination=Milovice,benatecka-vrutice&mode=transit&transit_mode=train|tram|subway|bus&transit_routing_preference=less_walking

While this https works perfectly in any browser and returns a JSON format, when I try to fetch it in my javascript appliacation it is always blocked by CORS policy.

console response

I thought it had something to do with my Google Studio Project setup because when I try to fetch from some other APIs in javascript it works just fine. I tried to read some articles about this issue but could not find anything useful.

I will be grateful for any help! Daniel


Solution

  • CORS Policy is a standard mechanism in browsers, which is responsible for how the server shares data with the client. In your case you get this error in your application because of the server of the Google Platform API doesn't allow sharing data to others, when the request is coming from a browser application e.g via a fetch call.

    Why does your https call works in any browser? If you take the requested url from your fetch call and request this URL directly in the browser instead of your application, than there is no CORS Policy.

    How to solve your issue:

    Normally if you are the owner of the requested server, you can add access control headers to the server response to permit or deny client requests. But this is not possible in your case, because you are not the owner of the Google Platform API. What you can do is creating a proxy server, which manages your fetch calls to the Google Platform API and send the data to your client application.

    Update: Thanks to @MrUpsidown the solution is quite easy. You can use the Directions Service a Javascript API for maps. Instead of doing a fetch call to google maps you can use this api to request your data in your client without using a proxy server.