Calling Yelp API from frontend JavaScript code running in a browser

前端 未结 1 1502
感动是毒
感动是毒 2020-12-06 22:26

Would really appreciate anyone\'s help. I am relatively new to developing in React, using Mac OSX and Chrome as my browser. I have a small application that attempts to make

相关标签:
1条回答
  • 2020-12-06 23:02

    This cause of the problem is that https://api.yelp.com/ doesn’t support CORS.

    And there’s nothing you can in your own application code to fix that—no matter what you try, you can’t change the fact that https://api.yelp.com/ doesn’t support CORS.

    Apparently the Yelp API does support JSONP though; see for example Yelp API Origin http://localhost:8888 is not allowed by Access-Control-Allow-Origin.

    So using https://api.jquery.com/jquery.getjson/ or similar in your frontend code would allow you make requests to the Yelp API cross-origin from your frontend code.


    A related issue in the GitHub issue tracker for the Yelp API examples repo confirms no CORS:

    TL;DR: No CORS is not supported by api.yelp.com

    And another related issue:

    As I answered in #99 , we do not provide the CORS headers necessary to use clientside js to directly make requests to the api.

    Both of the comments cited above are from a Yelp engineer.

    So what the means is, there’s no way your frontend JavaScript code can make requests directly to Yelp API endpoints and get normal responses (as opposed to JSONP responses).

    Specifically, because responses from the https://api.yelp.com/v3/businesses/search API endpoint don’t include the Access-Control-Allow-Origin response header, browsers will not allow your frontend JavaScript code to access those responses.

    Also, because your request includes the Authorization and a Content-Type header with the value application/json, your browser does a CORS preflight options request before ever attempting the actual GET request you’re trying to send.

    And that preflight is what’s specifically failing in this case. But any other request you make from the frontend JavaScript code to that API endpoint would also fail—even if it didn’t trigger a preflight.

    0 讨论(0)
提交回复
热议问题