Farah10
Farah10

Reputation: 91

Node JS GET by ID throwing 404 but with correct response

I have a GET request where I am trying to find a movie in my database by ID. I keep getting a 404 error in Postman, but when I log the response I am getting everything I need. I've been going round in circles now, so I'm sure I just missed something small, but I can't figure out what I'm doing that is throwing a 404.

This is in my 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()
        },
}

Upvotes: 0

Views: 406

Answers (1)

Đăng Khoa Đinh
Đăng Khoa Đinh

Reputation: 5411

If you found a movie from the database, you need to send the response to the client.

Replace

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;

by :

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

Upvotes: 1

Related Questions