node.js - 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.
解决方案
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:
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.
推荐阅读
- linux - 谁能解释一下下面的表达
- php - PHP - 同时最大脚本/任务
- python - 这与字典有关
- javascript - 在一个表单中选择单选按钮后显示另一个表单并在提交后返回
- yii2 - 在 Yii2 GridView 过滤中添加复选框
- kubernetes - Kubernetes 上的配额标签
- grid - Netlogo:是否可以有不同的补丁大小来节省建模计算时间?
- django - ImageField : 如何在 django 中处理图像文件
- wordpress - Slim API URL 在 wordpress 子文件夹中显示 404
- apache-flink - 如何将 flink 任务或背压相关的指标导出到 prometheus?