Node JS GET 通过 ID 抛出 404 但响应正确

Node JS GET by ID throwing 404 but with correct response

我有一个 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()
        },
}

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

替换

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});