【发布时间】:2020-02-17 16:31:49
【问题描述】:
我尝试像这样使用Cat Facts API:
const URL = "https://catfact.ninja/fact?limit=1" // In browser, this displays the JSON
fetch(URL).then(response=> {
console.log(response);
return response.json();
}
);
但我得到了
跨域请求被阻止:同源策略不允许读取位于https://catfact.ninja/fact?limit=1 的远程资源。 (原因:CORS 标头“Access-Control-Allow-Origin”缺失)。
TypeError:尝试获取资源时出现 NetworkError。
所以在尝试之后
fetch(URL, {mode:'no-cors'})
.then(response=> {
console.log(response);
return response.json();
}
);
我现在明白了
Response { type: "opaque", url: "", redirected: false, status: 0, ok: false, statusText: "", headers: Headers, body: null, bodyUsed: false }
SyntaxError: JSON.parse: JSON 数据的第 1 行第 1 列的数据意外结束
我从here 了解到,我将无法按预期使用此 API。但如果是这样,它的目的是什么以及它打算如何使用(this info 没有说明问题)?
【问题讨论】:
标签: javascript response fetch-api