当我尝试从Tibia API获取JSON时,我得到了两件事。
错误:tibia.js:8未捕获(已承诺)语法错误:输入意外结束
警告:跨域读取阻止(CORB)阻止了跨域响应https://api.tibiadata.com/v2/characters/Burdeliusz.json
class Tibia {
constructor() {}
async getCharacter(char) {
const characterResponse =
await fetch(`https://api.tibiadata.com/v2/characters/${char}.json`, {
mode: 'no-cors'
});
const character = await characterResponse.json();
return {
character
}
}
}
我搜索了类似的问题,但找不到解决方法。
答案 0 :(得分:-1)
这是因为端点未在响应标头中传递正确的参数。
标题应包括:
"Access-Control-Allow-Origin" : "*",
"Access-Control-Allow-Credentials" : true
我使用Postman进行了测试,响应中包含8个标题:https://api.tibiadata.com/v2/characters/Burdeliusz.json
Connection →keep-alive
Content-Length →683
Content-Type →application/json; charset=utf-8
Date →Thu, 09 Aug 2018 20:05:30 GMT
Server →nginx/1.10.3
Strict-Transport-Security →max-age=63072000; includeSubdomains; preload
X-Content-Type-Options →nosniff
X-Frame-Options →DENY
访问控制允许来源示例:https://api.spacexdata.com/v2/launches
Access-Control-Allow-Origin →*
CF-RAY →447cd76c595fab66-YYZ
Connection →keep-alive
Content-Encoding →gzip
Content-Type →application/json; charset=utf-8
Date →Thu, 09 Aug 2018 20:06:08 GMT
Expect-CT →max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct"
Server →cloudflare
Set-Cookie →__cfduid=d1dce3c5d11de37f960c7b47dc4f7d6701533845168; expires=Fri, 09-Aug-19 20:06:08 GMT; path=/; domain=.spacexdata.com; HttpOnly; Secure
Strict-Transport-Security →max-age=15552000; includeSubDomains
Transfer-Encoding →chunked
Vary →Accept-Encoding, Origin
X-Cache-Status →EXPIRED
X-Content-Type-Options →nosniff
X-DNS-Prefetch-Control →off
X-Download-Options →noopen
X-Frame-Options →SAMEORIGIN
X-Response-Time →151ms
X-XSS-Protection →1; mode=block
您可以尝试让tibiadata人员添加标题
OR
使用代理访问端点:http://jsfiddle.net/RouzbehHz/b95vcdhm/2/
var proxyUrl = 'https://cors-anywhere.herokuapp.com/',
targetUrl = 'https://api.tibiadata.com/v2/characters/Burdeliusz.json'
fetch(proxyUrl + targetUrl)
.then(blob => blob.json())
.then(data => {
console.table(data);
document.querySelector("pre").innerHTML = JSON.stringify(data, null, 2);
return data;
})
.catch(e => {
console.log(e);
return e;
});
您可以重新创建代理服务器:
git clone https://github.com/Rob--W/cors-anywhere.git
cd cors-anywhere/
npm install
heroku create
git push heroku master