![](/img/trans.png)
[英]Attempting to log JSON response from REST API in JavaScript using Fetch
[英]empty response from rest api using javascript fetch method (got a Json response on Postman)
设法在 Postman 中获得 JSON 响应,但在控制台中得到一个空响应,没有任何错误。
这是代码:
function getFetch() {
const url = `https://fantasy.premierleague.com/api/bootstrap-static/`;
let requestOptions = {
method: "GET",
redirect: "follow",
mode: 'no-cors',
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET",
"Access-Control-Allow-Headers": "x-requested-with"
};
fetch(
"https://fantasy.premierleague.com/api/bootstrap-static/",
requestOptions
)
.then((response) => response.text())
.then((result) => console.log(result))
.catch((error) => console.log("error", error));
}
假设您在浏览器中尝试,客户端:
跨域mode: 'no-cors'
请求 无法访问响应体和响应头,基本上是盲目发送数据但看不到结果。
那些Access-Control-…
标头不是针对请求的,而是针对服务器响应的。 如果服务器用它们进行响应,则响应将从所有来源读取。 (前提是此类请求不受mode: no-cors
。)
您可以看到,无论您获取什么,响应始终为status: 0
和ok: false
:
function runFetch() { console.clear(); fetch( url.value, { mode: nocors.checked ? 'no-cors' : 'cors' }, ) .then((response) => { console.log('Response status:', response.status, ', OK:', response.ok); return response.text() }) .then((result) => console.log("Result: »" + result + "«")) .catch((error) => console.log("error", error.message)); } runFetch()
<label>URL: <input id="url" value="https://fantasy.premierleague.com/api/bootstrap-static/" /></label> <br><label>no-cors: <input type="checkbox" id="nocors" checked /></label> <br><button onclick="runFetch()">run</button>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.