请求已成功发送,但在使用'fetch'时返回空的承诺

时间:2016-10-27 10:36:58

标签: javascript promise cors fetch-api

我使用React并获取发送请求,如:

fetch(`http://www.bilibili.com/index/catalogy/1-3day.json`,{
        mode: "no-cors"
    }).then(r => r.json()).then(r => {
        console.log(r);
    }).catch(err => {console.log(err);})

并且响应在网络标签中

但它会抛出错误:

SyntaxError: Unexpected end of input
at SyntaxError (native)
at http://127.0.0.1:8888/js/video.bundle.js:30174:15

当我尝试记录承诺时,它似乎是一个奇怪的对象:

Response {type: "opaque", url: "", status: 0, ok: false, statusText: ""…}

this is the picture

有人可以帮忙吗?我真的很困惑这个

1 个答案:

答案 0 :(得分:0)

您无法向不支持cross origin resource sharing (CORS)的外部服务器发出请求。

通过在请求上设置no-cors模式,您明确告诉服务器发出副作用请求而无法访问其内容。这与您从第三方网站在HTML中放置<img>标记并且无法访问其内容时类似 - 它对调用代码不透明。

您需要在服务器端下载该json,然后从您自己的服务器上提供它以避免此问题。