【问题标题】:Node JS GET by ID throwing 404 but with correct responseNode JS GET by ID 抛出 404 但响应正确
【发布时间】:2021-07-29 02:02:31
【问题描述】:

我有一个 GET 请求,我试图通过 ID 在我的数据库中查找电影。我在 Postman 中不断收到 404 错误,但是当我记录响应时,我得到了我需要的一切。我现在一直在兜圈子,所以我确定我只是错过了一些小东西,但我不知道我在做什么是抛出 404。

这是在我的 App.js 中:

app.use('/myMovies', MovieRouter);

MovieRouter.js:

movieRouter
    .route('/:movie_id')
    .all(requireAuth)
    .all((req, res, next) => {
        const db = req.app.get('db')
        MovieService.getById(db, req.params.movie_id)
        .then(movie => {
            if(!movie) { // this runs fine
                return res.status(404).json({ error: `Movie doesn't exist`})
            }
            console.log('line 61: ', movie) // returns: line 61: { id: 867, title: 'Sliver', watched: false, user_id: 2 }
            res.movie = movie
            console.log('line 63: ', res.movie) // returns: line 63: { id: 867, title: 'Sliver', watched: false, user_id: 2 }
            next()
            return movie;
        })
        .catch(next)
    })

MovieService.js:

const MovieService = {
    getById(db, id) {
            return db.from('your_movie_list').select(
                'your_movie_list.id',
                'your_movie_list.title',
                'your_movie_list.watched',
                'your_movie_list.user_id',
            )
            .where('your_movie_list.id', id).first()
        },
}

【问题讨论】:

    标签: javascript node.js get http-status-code-404


    【解决方案1】:

    如果您从数据库中找到了一部电影,您需要将响应发送给客户端。

    替换

    console.log('line 61: ', movie) // returns: line 61: { id: 867, title: 'Sliver', watched: false, user_id: 2 }
    res.movie = movie
    console.log('line 63: ', res.movie) // returns: line 63: { id: 867, title: 'Sliver', watched: false, user_id: 2 }
    next()
    return movie;
    

    作者:

    console.log('line 61: ', movie);
    res.json({movie : movie});
    

    【讨论】:

    • 哦,好的,成功了,谢谢。但现在我有点困惑,因为我有另一个路由器文件,我在其中按 ID 获取用户配置文件,并且我有“res.profile = profile”,这很有效。我看到的唯一区别是配置文件是单个对象,而电影结果是对象数组。对不起,如果这听起来很傻,我想我不明白两者之间的区别。
    • 在使用 Express 时,我使用 .send().json() 和其他类似的方法向客户端发送响应。您可以查看文档here。我认为您的用户路线中也有同样的事情。顺便说一句,老实说,我很少看到像res.profile = profile 这样的东西。
    猜你喜欢
    • 2013-11-16
    • 2011-08-27
    • 2012-02-25
    • 2011-03-27
    • 2022-06-17
    • 1970-01-01
    • 1970-01-01
    • 2021-04-17
    • 1970-01-01
    相关资源
    最近更新 更多