【发布时间】:2021-03-12 16:20:29
【问题描述】:
我有一个 API 可以将数据更新到数据库中。
我正在使用 Fetch API 将数据发送到服务器 API 以将数据存储在数据库中。
如果网络服务器无法将数据更新到数据库,它会返回 500 错误代码和错误消息。
响应 JSON 如下:
{"status":"error","message":"Some wrong when update roster data."}
我的问题是我无法将消息转发给 fetch API 调用者。
这是我的 fetch API 源代码:
static async fetchAPI(url,method,getParams,postParams){
if (getParams){
const paramsObject = new URLSearchParams(getParams);
const queryString = paramsObject.toString();
url+="?"+queryString;
}
url="/rosterWeb"+url;
console.log("=======================");
console.log("url="+url);
console.log("method="+method);
console.log("getParams="+getParams);
console.log("postParams="+postParams);
console.log("=======================");
return fetch(url,
{
body: JSON.stringify(postParams),
headers:{
'Content-Type': 'application/json'
},
"method":method || 'GET',
})
.then(response =>{
if (response.ok){
return response.json();
} else {
if (response.status===500){
response.json()
.then(json=>{
throw new Error(json.message);
})
}
}
})
.catch(error =>{
console.error('Error:', error);
});
}
这是我的中间件代码 sn-p:
import Utility from './Utility';
export default class Roster{
..............
.......
constructor(){
this.saveToDB=async(data)=>{
return await Utility.fetchAPI(*saveDataURL*,POST',null,rosterData);
}
}
}
这是我的 UI 组件代码 sn-p:
export default function ButtonPanel(){
..............................
async function saveDataToDB(){
let roster=new Roster();
await roster.saveRosterToDB({
........................
...........................
})
.then(result=>{
console.log("Update Success")
})
.catch(error=>{
console.log("ButtonPanel Exception Caught");
console.log(error);
})
/*
try{
let result=await roster.saveRosterToDB({
month:rosterMonth.getMonth()+1,
preferredShiftList:rosterData.preferredShiftList,
rosterList:rosterData.rosterList,
year:rosterMonth.getFullYear(),
})
console.log(result);
}catch(error){
console.log("Exception caught.");
console.log(error.message);
};
*/
roster=null;
}
}
当我执行 Roster.saveRosterToDB 方法时,无论是 try-catch 还是 then-catch 结构,它也返回以下错误:
`Unhandled Rejection (Error): Some wrong when update roster data.
(anonymous function)
c:/Users/knvb/workspace/rosterWeb_react_node/src/utils/Utility.js:91`
“更新名册数据时出现一些错误”来自响应 JSON。
ButtonPanel.saveDataToDB 将语句“更新成功”打印到控制台。
我试图通过异常将消息从服务器转发到 ButtonPanel。
但是,异常/错误没有被触发,我该如何解决?
【问题讨论】:
-
我将相关信息添加到我的问题文本中。请检查。
-
我建议您查看
axios的 XHR。我通常发现它比fetchapi 更容易使用,并且更容易编码。它也有大量的追随者。我很感激这并不能完全回答您的问题,但它会让事情变得更容易。
标签: javascript reactjs fetch