【问题标题】:Unhandled promise rejection Error: Cannot read property 'json' of undefined未处理的承诺拒绝错误:无法读取未定义的属性“json”
【发布时间】:2017-12-21 12:42:38
【问题描述】:
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'”。请建议我任何解决方案。

提前致谢。

【问题讨论】:

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


    【解决方案1】:

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

    要处理 fetch Promise 拒绝,您需要这样做:

    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。

    【讨论】:

    • 它不适用于 POST 方法,因为它会为 answers.length 时间创建完整的数据,我的意思是整个数据进入一个循环
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-30
    • 2018-05-06
    • 2016-10-28
    • 1970-01-01
    • 2020-02-06
    • 2019-01-11
    • 2017-05-29
    相关资源
    最近更新 更多