【问题标题】:CORS header ‘Access-Control-Allow-Origin’ missing - Access-Control-Allow-Origin already given缺少 CORS 标头“Access-Control-Allow-Origin” - Access-Control-Allow-Origin 已给出
【发布时间】:2019-02-07 01:01:05
【问题描述】:

我已经给出了 axios 调用的标头,但我仍然收到此错误。我已经尝试了很多。 代码如下: -

class Test extends React.Component {
  constructor(props) {
    super(props);
    this.state = { address: '' };
  }

  componentDidMount(){
      axios({type:'get',url:'https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=Chennaiined&radius=1000&keyword=fdtbf&key=KEY'},{header:{'Access-Control-Allow-Origin': 'https://maps.googleapis.com'}})
      .then(res=> alert("response"+res))
  }

  render() {
    return (
        <div>
       <span>test</span>
        </div>

    );
  }
}

我给了* 而不是https://maps.googleapis.com,但仍然遇到同样的错误。

提前致谢

【问题讨论】:

标签: reactjs cors axios


【解决方案1】:

据我所知,您必须使用 Google Maps 的 Place API,而不是 Axios。

例子:

var request = {
query: 'Museum of Contemporary Art Australia',
fields: ['photos', 'formatted_address', 'name', 'rating', 
'opening_hours', 'geometry'],
};

service = new google.maps.places.PlacesService(map);
service.findPlaceFromQuery(request, callback);

正如@sideshowbarker 所说:

像这样使用 Maps JavaScript API(通过脚本元素加载库,然后使用 google.maps.Map 和其他 google.maps.* 方法)是向来自运行浏览器的前端 JavaScript 代码的 Google Maps API。

Google 故意不允许通过使用其他此类库中的 axios 或 AJAX 方法发送的请求,也不允许直接使用 XHR 或 Fetch API 来访问 Google Maps API。

您可以在这里找到更多信息:https://developers.google.com/maps/documentation/javascript/places#place_search_requests

另外,已经有重复的问题:CORS and Angular $http GET to Google Places APIGoogle Maps API: No 'Access-Control-Allow-Origin' header is present on the requested resource

【讨论】:

    猜你喜欢
    • 2018-03-28
    • 2021-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-19
    • 1970-01-01
    • 2021-12-07
    • 2023-03-21
    相关资源
    最近更新 更多