未处理的承诺拒绝错误:无法读取属性' json'未定义的

时间:2017-12-21 12:42:38

标签: json reactjs api react-native map-function

answers.map((answer, index) => {
  answer_text = answer.answer_text;
  id = answer.id;
  return fetch(BASE_URL + url, {
    method: 'PUT',
    headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json',
      'Authorization': 'Token token=' + token
    },
    body: JSON.stringify({
      question: {
        answers_attributes: {
          '0': {
            answer_text: answer_text,
            id: id
          }
        }
      }
    })
  });
})

我使用了map函数,因此在每个地图上都应该转到JSON.stringify并赋值。但是我得到了错误"未处理的承诺拒绝TypeError:无法读取属性' json'未定义"。请建议我任何解决方案。

提前致谢。

1 个答案:

答案 0 :(得分:3)

在这里你要创建一个fetch promises数组,之后我们需要更多关于你如何处理这些promises的信息,我想你正在尝试某个地方使用.then(res => res.json())从这些promises中获得响应,但是你的服务器响应不是json格式。

要处理取消承诺拒绝,您需要执行以下操作:

fetch(smth)
.catch(error => //handle the error e.g. console.log(error))

要查看您的请求json正文中是否有问题,您可以在服务器端登录或在发送之前记录它,您还可以记录服务器响应,尝试这样来识别出错:

answers.map((answer, index) => {
  answer_text = answer.answer_text;
  id = answer.id;
  const body = JSON.stringify({
      question: {
        answers_attributes: {
          '0': {
            answer_text: answer_text,
            id: id
          } }
      }
    })
console.log('Json body request :', body);
  return fetch(BASE_URL + url, {
    method: 'POST',
    headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json',
      'Authorization': 'Token token=' + token
    },
    body
  }).then(res => {
    console.log('server response :', res);
    return res;
  }).catch(err => console.log('Fetch error :', err));
 })

我建议使用Postman之类的应用来测试来自api服务器的响应(更轻松,更快速地调试来自API的请求/响应)

编辑:我也认为你想做一个POST请求而不是PUT。