I am just starting to learn how to make requests to APIs using Javascript, and I have been stuck on the following for a few hours.
I used the following public API: http://www.penguinrandomhouse.biz/webservices/rest/
The issue is that, when I was using XMLHttpRequest, I am always running into an error. At first I didn’t include the content-type in header I got a 404, and when I included it, the error I have got a CORS error. The following is the code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<title>Request book</title>
<style>
...
</style>
</head>
<body>
<section class="preview">
<div id="return_content"></div>
</section>
<script>
let request = new XMLHttpRequest();
const url = "https://reststop.randomhouse.com/resources/authors";
request.open("GET", url);
let content = {
lastName : "Grisham",
}
request.setRequestHeader('Content-type', 'application/json');
/* I did not add this at first, but it seems like the
default content type for XHR is not what the API wants*/
request.send(JSON.stringify(content));
request.onreadystatechange = () => {
if (this.readyState == 4 && this.status == 200){
console.log(request.responseText);
/* let content_div = document.querySelector('#return_content');
content_div.innerText = request.responseText; */
}
}
</script>
</body>
</html>
The error message is as the following:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://reststop.randomhouse.com/resources/authors. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). Status code: 200
But I tried sending the request first with Axios in node.js with the following, it goes totally fine; so I assume it must be something wrong with my request. However, from my understanding the CORS policy should be set by the server, and it seems like from this post I cannot set Access-Control-Allow-Origin — it is supposed to be something provided by the server-side.
It seems like something is missing in the request but I really have no idea. Any help or hint would be appreciated!