【问题标题】:I am trying to do a Yelp Fusion (V3) API call in JavaScript我正在尝试在 JavaScript 中进行 Yelp Fusion (V3) API 调用
【发布时间】:2017-05-22 13:21:24
【问题描述】:

我有这个 API 调用在 Postman 中工作,但是当我将代码复制到我的 JS 代码中时,我收到以下错误:

XMLHttpRequest 无法加载 https://api.yelp.com/v3/businesses/search?term=restaurant&latitude=40.82783908257346&longitude=-74.10162448883057
对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。
因此,Origin 'null' 不允许访问。
响应的 HTTP 状态代码为 500。

我的 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);

根据 Yelp 文档 - Yelp 不支持 CORS - 所以 CORS 不是问题。

【问题讨论】:

标签: javascript ajax


【解决方案1】:

我能够在客户端使用 Fetch 毫无问题地实现它。我怀疑它可能是您的标题之一。

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);
  })

【讨论】:

  • 这个答案的 url 不正确,问题是使用最新的 yelp fusion API (v3)。
猜你喜欢
  • 1970-01-01
  • 2023-03-18
  • 2017-11-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多