使用fetch在react中进行post调用时,获取“未捕获(承诺)SyntaxError:JSON中位置0处的意外令牌H”错误

问题描述 投票:1回答:1

该请求是成功的,正如我在日志中看到的那样,但是在浏览器上却给我一个错误:“未捕获(承诺)SyntaxError:JSON位置0处的意外令牌H”

用于进行调用的响应代码

fetch(url, {
  method: 'POST',
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    name: 'Testing'
  })
}).then(response => response.json())
  .then(json => console.log(json));

创建响应并从其发送消息的后端代码段

    responseJson =  (JsonNode)constructResponse("Hello from the backend");

    logger.log("Response: " + responseJson.toString());

    // Output the response
    OutputStreamWriter writer = new OutputStreamWriter(outputStream, "UTF-8");
    writer.write(responseJson.toString());
    writer.close();

编辑2:

将代码更新到下面:

fetch(url, {
    method: 'POST',
    body: JSON.stringify(data),
    headers:{ 'Content-Type': 'application/json' }
 })
 .then(res => res.json())
 .catch(error => console.error('Error:', error))
 .then(response => console.log('Success:', response));

它给我这个错误:“错误:语法错误:JSON在位置0处出现意外的标记H”。虽然我可以在日志中看到,但发帖请求成功完成。

reactjs fetch-api
1个回答
0
投票

所以我想这与react或fetch api没有关系。后端代码未在json中发送响应,而我正在尝试此“ .then(res => res.json())”。当我删除它时。有效。因此,总而言之,我需要更新我的Java后端api代码以发送json文件。

© www.soinside.com 2019 - 2024. All rights reserved.