Warm tip: This article is reproduced from serverfault.com, please click

Stackexchange REST API has been blocked by CORS policy

发布于 2020-11-28 23:03:02

I needed to use the StackOverflow API to retrieve some data from the site. Actually, when I tried the first time to use the API I got an exception due to CORS policy.

Access to fetch at 'https://stackoverflow.com/users/myID/reputation' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

I understand that the reason why my request was blocked was that the header was not in the response. However, does not StackExchange API attach in the response header Access-Control-Allow-Origin? I'm doing something wrong in how I'm invoking the request?

Questioner
AndreaCostanzo1
Viewed
0
CertainPerformance 2020-11-29 07:09:33

does not StackExchange API attach in the response header Access-Control-Allow-Origin? I'm doing something wrong in how I'm invoking the request?

The Stack Exchange API permits client-side requests, but the page you're requesting is not the Stack Exchange API - it's just a plain Stack Exchange page, not the API endpoint designed for such things, so it doesn't have the required header.

If you want to use the API properly, go through the documentation here and choose the endpoint you need. For an example using my user ID, one might use the following code:

fetch('https://api.stackexchange.com/2.2/users/9515207/reputation?site=stackoverflow')
  .then(res => res.json())
  .then(console.log);

api.stackexchange.com has the proper headers: access-control-allow-origin: *, which allows for client-side scripts to request it.

since this request is for a trial project, can I implement a proxy using a free-tier of some platform? I see a lot of suggestions for Heroku but I'm not very familiar with that platform

For the more general case of a server that doesn't set the required headers, if you wanted to use one of their responses client-side, you would have to bounce the request off a relay server. You could either make your own app on Heroku (a good free option), or use something like https://cors-anywhere.herokuapp.com/