So I'm trying to set up a feed on my personal portfolio website to show my most recent couple blog posts. This is a simple Javascript frontend hosted on Netlify.
I've set up a fetch to the api for my articles, with api-key and everything. It works in Postman, but once I'm running it in Chrome I run into what I think is a CORS issue. The console puts out: Failed to load resource: net::ERR_BLOCKED_BY_CLIENT
and Failed to load resource: the server responded with a status of 404 ()
Here is my fetching code:
var myHeaders = new Headers();
myHeaders.append("api-key", "xxx");
var requestOptions = {
method: "GET",
headers: myHeaders,
redirect: "follow"
};
fetch("https://dev.to/api/articles/me/published?=", requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log("error", error));
Has anyone had success setting up an API call to their blog? Can anyone suggest how to get around this issue?
Googling this proves incredibly difficult for some reason.
Top comments (2)
Hi Helen, thanks a lot of reporting this, thanks @peter for tagging me!
Unfortunately it is a known issue:
API: Fetching endpoint /api/articles/me sometimes returns CORS error. #5877
Currently working with the api and I see that the endpoint gives CORS error, but on second request does it work. This do i only get while using /api/articles/me request.
To Reproduce
Expected behavior
To render 200 OK response
Desktop (please complete the following information):
we do have some issues with CORS (cross origin request sharing, aka calling a website from another website). By default browsers block these requests for security reasons.
While we plan to fix this we haven't got to it yet.
A possible solution, in the meantime, is illustrated by this user's post:
CORS Problem Workaround for Consuming DEV.TO API on Your Website
Jason Reed γ» Dec 14 '19 γ» 1 min read
which consists of having a server side page that does the API call.
A personal note: as you're writing a frontend website that calls a protected API (behind the DEV API key) you should know there's a potential for leakage if this page ever gets published (since the API key) resides in the HTML page or JS file. I suggest you look into doing that specific HTTP call on the server anyway, and have your JS client call your server that then calls DEV. Basically a proxy :)
Let me know if any of this isn't super clear, happy to help!
CC @rhymes and @maestromac who might have some advice and/or more info.