使用fetch API会发生输入错误的意外结束

时间:2017-11-23 13:32:54

标签: javascript json fetch-api

fetch('http://www.freegamesforyourwebsite.com/feeds/games/?
tag=platform&limit=100&format=json',
{
method:'GET',
mode:'no-cors',
dataType: 'json',
    headers: {
        'Accept': 'application/json'
    }  

}).then(response =>
response.json()).then(addImage).catch(e => requestError(e,'image'));

的console.log

SyntaxError: Unexpected end of input
 at fetch.then.response ((index):159)
 at <anonymous>

我尝试使用带有cros平台的json获取,为什么Google开发人员工具中的请求标题向我显示提供请求标题。预览部分可以显示我的json响应,但响应承诺之后的承诺无法读取数据和错误发生在上面的控制台日志中所示。我获取的URL是每个人都可以使用的开源。

感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

你说mode:'no-cors',所以fetch没有尝试跨越原点读取数据(默认情况下是禁止的),并且它不会抛出错误(因为你告诉了)它你不想尝试读取原始数据。)

将其更改为mode: "cors"

确保您请求数据的服务器授予您使用Access-Control-Allow-Origin标题读取响应的权限。

另见this answer about the Same Origin Policy