【问题标题】:Why am I getting a Mongoose error when making a PUT request to an empty route?为什么在向空路由发出 PUT 请求时出现 Mongoose 错误?
【发布时间】:2020-04-27 09:00:37
【问题描述】:

我有这个函数可以向/api/lyric/tag发出 axios put 请求

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"

我是不是疯了?

【问题讨论】:

    标签: express mongoose axios


    【解决方案1】:

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

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

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

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

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

    【讨论】:

    • 好的,谢谢!我有路线/api/lyric/:_id。我会在 2 分钟内接受答复。
    猜你喜欢
    • 2022-01-10
    • 1970-01-01
    • 2023-04-08
    • 1970-01-01
    • 2022-07-07
    • 1970-01-01
    • 2019-09-29
    • 1970-01-01
    • 2019-08-13
    相关资源
    最近更新 更多