2016-05-12 45 views
2

这是我的功能
不知道问题出在哪里阵营原生取“POST”请求投掷“语法错误:JSON输入意外结束”,在Android的

fetchData() { 
     fetch(REQUEST_URL, { 
     method: 'POST', 
     headers: { 
     'Accept': 'application/json', 
     'Content-Type': 'application/json', 
     }, 
     body: JSON.stringify({ 
     Request : 'menu', 
     active : '1', 
     }) 
    }).then((response) => response.json()) 
    .then((responseData) => { 
     this.setState({ 
       menu: responseData.Response, 
      }); 
    }) 
    .catch((error) => { 
     console.warn('error',error); 
    }) 
    .done(); 
     } 

请指出问题在功能

+0

任何一个有一些想法? –

回答

0

这个错误的可能原因是你的服务器不返回一些无效的JSON(可能不是JSON,就像404页面或类似的东西)。

+0

但邮递员我有我的服务器@oblador的回应 –

1
then((response) => response.json()) 
        ^^^^^^^^^^^^^ I think this is the problem 

与响应状态代码不等于2XX不会进入catch当您使用获取API,因此您可以JSON.parse的东西,如HTML页面或纯文本流。

在将响应解析为JSON之前,您应该检查是否response.ok === true

0

如果您将请求内容类型设置为application/json,那么它可能会发送预检请求来检查CORS。

在我的React应用程序(不是React-Native)中,我遇到了跨域问题。我的服务器不支持预检要求,所以响应的样子:

{ body: null, status: 0, ok: false, }

这是造成response.json()即使失败了,虽然我在Chrome浏览器开发工具预期的JSON响应。

就我而言,我将请求内容类型更改为application/x-www-form-urlencoded,它不需要预检请求。它按预期工作。

它可能无助于你的情况,但我希望它给你一些见解。

0

日志回复数据。 API可能会返回无效数据。

0

发生错误是因为您的响应无法转换为JSON格式。由于标题,响应正文或基于服务器的其他各种原因,可能会发生此问题。要走的路(因为显然响应不一致)是在尝试将响应转换为JSON之前执行服务器响应的附加验证。

您可以通过替换做到这一点:

.then((response) => response.json()) 

.then((response) => { 
    // In this case, we check the content-type of the response 
    if (response.headers.get('content-type').match(/application\/json/)) { 
    return response.json(); 
    } 
    return response; 
    // You can also try "return response.text();" 
}) 
相关问题