我得到一个服务器端错误:[AxiosError:请求失败,状态代码为500。很明显我的请求有问题,但不确定是什么。
此react-native应用程序的控制台错误指向updateError函数:费用-上下文.js:76:6
调用堆栈
x1c 0d1x这是数据在组件之间移动的方式:
ExpenseForm.js是构造expenseData的地方:
async function submitHandler() {
const expenseData = {
amount: +inputs.amount.value,
date: new Date(inputs.date.value),
description: inputs.description.value,
_id: inputs._id.value
}
之后,expenseData被传递给确认器:
function confirmHandler(expenseData) {
if (isEditing) {
expensesCtx.updateExpense(_id, expenseData)
console.log('expenseData', expenseData)
navigation.goBack()
} else {
expensesCtx.addExpense(expenseData)
navigation.goBack()
}
控制台日志expensieData的输出如下:
expenseData {"_id": "64e1aaad97da840a04ce64e5", "amount": 99.99, "date": 2023-08-19T00:00:00.000Z, "description": "Update Expense"}
然后,expenses-context.js中的updateData获取_id和expenseData:
async function updateExpense(_id, expenseData) {
try {
await axios.put(`http://localhost:8082/expenses2/${_id}`, expenseData);
dispatch({ type: 'UPDATE', payload: { _id: _id, data: expenseData } });
} catch (error) {
console.error('Error updating expense:', error);
}
}
最后,app.put在server.js中被调用,并传递了_id和expenseData:
await Expense.findByIdAndUpdate({ _id: ObjectId(_id) }, { $set: expenseData });
在上面的行中
app.put("/expenses2/:_id", async (req, res) => {
const _id = req.params._id;
try {
// Update the expense in the database based on expenseId and req.body
const expenseData = req.body
await Expense.updateOne({ _id: ObjectId(_id) }, { $set: { expenseData } });
res.json({ message: 'Expense updated successfully' });
} catch (error) {
console.error('Error updating expense:', error);
res.status(500).json({ error: 'An error occurred while updating the expense' });
}
});
1条答案
按热度按时间ac1kyiln1#
这可能是因为您在路由处理程序的updateOne方法中使用$set操作符的方式。您正在将整个expenseData对象设置为文档中的字段。相反,您应该直接将expenseData对象传递给$set。