我在 React 应用程序中向 API 发送 POST 请求时遇到问题。尝试保存清单时,我收到 500 服务器错误,并在控制台中收到以下错误消息:
我正在使用 fetch 来发出请求,并且我也尝试过使用 axios 库,但问题仍然存在。
这是我的请求的代码:
const accessToken = '29283b3ef76dcce0b65c77cf41f6cb86400920f2';
const baseURL = 'https://greenvelvet.alwaysdata.net/pfc';
const handleSaveChecklist = async () => {
// ... (other parts of the code)
try {
const response = await fetch(`${baseURL}/checklist/add`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${accessToken}`,
},
body: JSON.stringify(checklistData),
});
const data = await response.json();
console.log('Server response:', data);
setCreateMessage(`Checklist "${checklistData.title}" created.`);
} catch (error) {
console.error('Error saving the checklist:', error);
setCreateMessage(`Failed to create checklist. Error: ${error.message || 'Unknown error'}`);
}
};
此外,我已验证我的令牌是否正确,但我仍然在 JSON 响应中收到以下服务器错误:{"error":"Token is notknown"}
您对如何解决这个问题有什么建议吗?预先感谢您的帮助!
很难说。当前访问 https://greenvelvet.alwaysdata.net/pfc/checklist/add 给我 404 未找到错误。
我建议在 fetch 之后添加 if 语句,因为 fetch() 仅在用户离线或发生一些不太可能的网络错误(例如 DNS 查找失败)时才会拒绝承诺。根据 MDN,
if (!response.ok) {
throw new Error("Error happened");
}
只需尝试将“授权”放入引号中即可。