首页 > 解决方案 > Google maps API returning No 'Access-Control-Allow-Origin' with Node.js module

问题描述

I am using the node module @googlemaps/google-maps-services-js to make requests to the Google maps API. When I make requests to any of their API endpoints (e.g directions API, places API, etc), I get these errors:

xhr.js:125 Refused to set unsafe header "User-Agent"
xhr.js:125 Refused to set unsafe header "Accept-Encoding"
localhost/:1 Access to XMLHttpRequest at 'https://maps.googleapis.com/maps/api/directions/json?
destination=Universal%20Studios%20Hollywood&key=mykey&origin=Disneyland' from 
origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header
is present on the requested resource.

Here are the things I've tried:

1. I've tried accessing different API endpoints, (e.g instead of directions, places.)

2. I've tried adding headers manually, but I don't really know what headers i should add to make this work.

3. I have also tried accessing this API from my normal browser (Google). It returned a proper response, so it isn't an improper API key.

Also Note:

I have activated my API key, activated each of the APIs I want to use, and I have set up a billing account with Google Cloud Platform.

标签: node.jsgoogle-maps

解决方案


Not for browser

@googlemaps/google-maps-services-js is not compatible with browser environments because the Google server DOES NOT return the necessary CORS headers. This package is for Nodejs.

From the readme:

not for browser

Alternative [Preferred]

Use https://developers.google.com/maps/documentation/javascript/overview.

Your code will look similar to the following:

const directionsService = new google.maps.DirectionsService();
const request = {
    origin: 'Disneyland',
    destination: 'Universal Studios Hollywood',
    travelMode: 'DRIVING'
};
const response = await directionsService.route(request);

A directions tutorial is available.

Alternative 2

Proxy the directions endpoint through your own server and add CORS headers.


推荐阅读