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

问题描述 投票:0回答:1
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函数,因此在每个map上都应该转到JSON.stringify并赋值。但我收到错误“Unhandled promise rejection TypeError:无法读取未定义的属性'json'”。请建议我任何解决方案。

提前致谢。

json reactjs api react-native map-function
1个回答
3
投票

在这里你要创建一个fetch promises数组,之后我们需要更多关于你如何处理这些promise的信息,我想你正在尝试使用.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。

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