使用 Redux 创建一个 put api 请求
Creating a put api request using Redux
我正在使用 MERN 堆栈和 Redux。我发现很难创建 api 和更新 MongoDb 的操作。我有两个模型,我想通过 id 找到一个模型,然后用传入的另一个模型的对象更新它。这就是我的 api 和操作。谁能给我一些建议,告诉我如何完成这项工作,以及我如何通过要添加到 api 的评论?当我在 Postman 上测试它时它说它已经工作但是当我在 url 中使用一个 id 时没有返回任何对象。我还将 res.json(subject) 更改为 res.send("Put req success") 但此文本也未显示。请帮忙! :(
api
subjectRouter.put("/subject/:_id", (req, res) => {
Subject.findById(req.params._id, (err, subject) => {
if (err) {
res.send(err);
}
// what goes here to update the subject?
// the propery to be updated is 'comments'
// which is an array of comment objects
console.log(subject.json);
Subject.updateOne()
res.json(subject);
});
});
行动
export const updateSubject = () => (dispatch) => {
console.log("updateSubject called");
fetch("/api/subjects/Subject/:_id")
.then((res) => res.json())
.then((subject) =>
dispatch({
type: UPDATE_SUBJECT,
subjects: subject,
})
);
};
似乎 api 将 _id
作为参数,但您没有在 fetch 调用中传递它,这里试试这个:
export const updateSubject = (id) => (dispatch) => {
console.log("updateSubject called");
fetch(`/api/subjects/Subject/${id}`)
.then((res) => res.json())
.then((subject) =>
dispatch({
type: UPDATE_SUBJECT,
subjects: subject,
})
);
};
我正在使用 MERN 堆栈和 Redux。我发现很难创建 api 和更新 MongoDb 的操作。我有两个模型,我想通过 id 找到一个模型,然后用传入的另一个模型的对象更新它。这就是我的 api 和操作。谁能给我一些建议,告诉我如何完成这项工作,以及我如何通过要添加到 api 的评论?当我在 Postman 上测试它时它说它已经工作但是当我在 url 中使用一个 id 时没有返回任何对象。我还将 res.json(subject) 更改为 res.send("Put req success") 但此文本也未显示。请帮忙! :(
api
subjectRouter.put("/subject/:_id", (req, res) => {
Subject.findById(req.params._id, (err, subject) => {
if (err) {
res.send(err);
}
// what goes here to update the subject?
// the propery to be updated is 'comments'
// which is an array of comment objects
console.log(subject.json);
Subject.updateOne()
res.json(subject);
});
});
行动
export const updateSubject = () => (dispatch) => {
console.log("updateSubject called");
fetch("/api/subjects/Subject/:_id")
.then((res) => res.json())
.then((subject) =>
dispatch({
type: UPDATE_SUBJECT,
subjects: subject,
})
);
};
似乎 api 将 _id
作为参数,但您没有在 fetch 调用中传递它,这里试试这个:
export const updateSubject = (id) => (dispatch) => {
console.log("updateSubject called");
fetch(`/api/subjects/Subject/${id}`)
.then((res) => res.json())
.then((subject) =>
dispatch({
type: UPDATE_SUBJECT,
subjects: subject,
})
);
};