简体   繁体   English

我正在尝试在 JavaScript 中执行 Yelp Fusion (V3) API 调用

[英]I am trying to do a Yelp Fusion (V3) API call in JavaScript

I have this API call working in Postman, but when I copy the code into my JS code I get the following error:我在 Postman 中有这个 API 调用,但是当我将代码复制到我的 JS 代码中时,我收到以下错误:

XMLHttpRequest cannot load https://api.yelp.com/v3/businesses/search?term=restaurant&latitude=40.82783908257346&longitude=-74.10162448883057 . XMLHttpRequest 无法加载https://api.yelp.com/v3/businesses/search?term=restaurant&latitude=40.82783908257346&longitude=-74.10162448883057
Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。
Origin 'null' is therefore not allowed access.因此,不允许访问 Origin 'null'。
The response had HTTP status code 500.响应的 HTTP 状态代码为 500。

My AJAX call (with Bearer altered for security):我的 AJAX 调用(为了安全而更改了 Bearer):

var settings = {
  "async": true,
  "crossDomain": true,
  "url": "https://api.yelp.com/v3/businesses/search?term=restaurant&latitude=40.82783908257346&longitude=-74.10162448883057",
  "method": "GET",
  "headers": {
    "authorization": "Bearer xxxxxxxxxxxxx_xxxxxxxxxxxxxxxxxxxxxx-xxxxxxxxxxxxxxxxxxxxxxxxxxxxx-xxxxxxxxxxxx_xxxxxxxxxxxxxxxxxxxxxxxxxxxx",
    "cache-control": "no-cache",
    // "postman-token": "1c66878e-c740-e10d-8d9a-71d731547d2e"
  }
}


$.ajax(settings).done(function (response) {
  console.log(response);

According to the Yelp documentation - Yelp does not support CORS - so CORS is not the issue.根据 Yelp 文档 - Yelp 不支持 CORS - 所以 CORS 不是问题。

I was able to implement it without any issues on the client-side using Fetch.我能够使用 Fetch 在客户端没有任何问题地实现它。 I suspect it might be one of your headers.我怀疑它可能是您的标题之一。

fetch('https://api.yelp.com/oauth2/token?client_id=<CLIENT_ID>&client_secret=<CLIENT_SECRET>', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded',
  },
  body: JSON.stringify({
    grant_type: 'client_credentials',
  })
})
  .then((res) => res.json())
  .then((resJSON) => {
    this.setState({ access_token: resJSON.access_token });
    console.log(resJSON)
  })
  .then(() => {
    fetch('https://api.yelp.com/v3/businesses/search?location=12345', {
      method: 'GET',
      headers: {
        'authorization': 'Bearer ' + this.state.access_token
      }
    })
    .then((res) => res.json())
    .then((resJSON) => {
      console.log('resJSON', resJSON)
    })
  })
  .catch((err) => {
    console.log('err', err);
  })

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM