Unhandled promise rejection Error: Cannot read property 'json' of undefined
Unhandled promise rejection Error: Cannot read property 'json' of undefined
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 并分配值。但是我得到了错误 "Unhandled promise rejection TypeError: Cannot read property 'json' of undefined"。请给我任何解决方案。
提前致谢。
这里你正在创建一个获取承诺的数组,我们需要更多关于你如何处理这些承诺的信息,我想你正在尝试在某个地方使用 .then(res => res.json())
从这些承诺中获得响应,但是你的服务器响应不是 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 调试 request/responses 更容易和更快)
编辑:我还认为您想执行 POST 请求而不是 PUT。
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 并分配值。但是我得到了错误 "Unhandled promise rejection TypeError: Cannot read property 'json' of undefined"。请给我任何解决方案。
提前致谢。
这里你正在创建一个获取承诺的数组,我们需要更多关于你如何处理这些承诺的信息,我想你正在尝试在某个地方使用 .then(res => res.json())
从这些承诺中获得响应,但是你的服务器响应不是 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 调试 request/responses 更容易和更快)
编辑:我还认为您想执行 POST 请求而不是 PUT。