【发布时间】:2022-02-02 21:55:51
【问题描述】:
我刚刚开始学习如何使用 Javascript 向 API 发出请求,并且我已经坚持了几个小时。
我使用了以下公共 API: http://www.penguinrandomhouse.biz/webservices/rest/
问题是,当我使用 XMLHttpRequest 时,我总是遇到错误。起初我没有在标题中包含内容类型,我得到了 404,当我包含它时,错误我得到了一个 CORS 错误。 以下是代码
<!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>
错误信息如下:
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
但我尝试先在 node.js 中使用 Axios 发送请求,如下所示,一切正常;所以我认为我的请求一定有问题。但是,据我了解,CORS 策略应该由服务器设置,并且从 this post 看来我无法设置 Access-Control-Allow-Origin - 它应该是服务器端提供的东西。
请求中似乎缺少某些内容,但我真的不知道。任何帮助或提示将不胜感激!
【问题讨论】:
标签: api http xmlhttprequest preflight