[英]Console.log inside then from fetch not working
我正在尝试从 expo 应用程序(反应本机)调试代码,该应用程序将 json 发布到端点。 我在 fetch 之后的 then 子句中添加了 console.log 语句,但它们根本没有打印:其他代码运行良好:S
sendMessage: (
token,
data
) => {
return new Promise((resolve, reject) => {
const body = {
...data,
};
fetch(`${URI_BACKEND}api/create`, {
method: 'POST',
headers: {
Authorization: `Bearer ${token}`,
'Content-Type': 'application/json',
},
body: JSON.stringify(body),
})
.then((response) => {
console.log("RESPONSE FROM BACKEND", response);
showToastGlobal("success", "top", "Saved", "Message saved successfully");
return response.json();
})
.then(json => resolve(json))
.catch(error => {console.log("ERROR FROM THE BACKEND", error); reject(error);});
});
},
showToastGlobal function 正在执行,因为我可以在应用程序中看到 toast,知道我做错了什么吗? 没有错误日志,也没有响应日志...
更新:添加调用者 function
const sendWholeMessage = (messageId, messageToSend, images, timestamp, userId) => {
API.sendMessage(token, messageToSend)
.then(response => {
if (images[0]) {
console.log("Sending images...");
API.saveImages(token, images)
.then(result => console.log("Response img:", result))
.catch(error => console.log("ERROR sending images to backend", error));
}
console.log("Response Message:", response);
...
deleteLocalCopyOfMessage(messageId);
console.log("Saving...")
});
}
“响应消息”和“正在保存...”控制台日志都打印正常
更新2:改变
console.log("RESPONSE FROM BACKEND", response);
至
console.log("RESPONSE FROM BACKEND", response.status);
打印到控制台,或者从 console.log 中删除第二个参数(只是字符串)也可以,所以尝试打印响应 object 会导致 console.log 语句被忽略,关于为什么会发生这种情况的任何想法?
使用 fetch API 未收到响应。
fetch API 需要两个步骤来获取响应,所以我建议您在第二个 then() 子句中检索响应:
fetch(`${URI_BACKEND}api/create`, {
method: 'POST',
headers: {
Authorization: `Bearer ${token}`,
'Content-Type': 'application/json',
},
body: JSON.stringify(body),
})
.then((response) => {
return response.json();
})
.then(json =>
console.log("RESPONSE FROM BACKEND", json);
showToastGlobal("success", "top", "Saved", "Message saved successfully");)
.catch(error => {console.log("ERROR FROM THE BACKEND", error); reject(error);});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.