首页 > 解决方案 > 为什么在向空路由发出 PUT 请求时出现 Mongoose 错误?

问题描述

我有这个功能,它使 axios 提出请求/api/lyric/tag

const addTag = async (name, tagId, lyricId) => {
    const body = {name, tagId, lyricId};
    await axios.put(`/api/lyric/tag`, JSON.stringify(body), { headers: {'Content-Type': 'application/json'} });
}

目前该路线/api/lyric/tag完全是空的:

// @route   PUT api/lyric/tag
// @desc    Add tag to lyric
// @access  Private
router.put('/tag', auth, async (req, res) => {


});

然而由于某种原因,每次 axios 发出 put 请求时我都会收到此错误: Cast to ObjectId failed for value "tag" at path "_id" for model "lyric"

我失去理智了吗?

标签: expressmongooseaxios

解决方案


将 res.send("OK") 或 res.json({ message: "OK" }) 放在路由的末尾。

您收到此错误是因为您没有响应请求者。

或者这条路线正在匹配另一条路线......

/api/lyric 有什么路线吗?如果它有,在某种程度上等于 /api/lyric/:_id,它就会被调用。

尝试将路由更改为 /api/lyric/tag/update。它不是 REST,但您的路线将被调用。然后,您将需要重构 api 以使其具有凝聚力。


推荐阅读