Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

"Cannot GET /api/users/2" why is my GET request not working?

"Cannot GET /api/users/2" why is my GET request not working for a user with an id of 2?

The query http://localhost:3000/api/users works but i’m trying to find an individual user based on their id and this is not working in my code below.

const express = require('express');
const app = express();

const users = [
    [{name: 'liam', id: 1}, {name: 'jon', id: 2}]
];

app.get('/api/users', (req, res ) => {
    res.send(users);
})


app.get('/api/users:id', (req, res ) => {
    const id = parseInt(req.params.id)
    const user = users.filter(u => u.id === id) [0]
    res.send(user)
})

app.listen(3000, () => console.log('Listening on port 3000.......'));

When I do "http://localhost:3000/api/users/1" nothing displays in my browser.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I have updated the code to app.get('/api/users/:id'

>Solution :

You’re missing a slash:

app.get('/api/users/:id', …)

Also, you have an array-in-an-array, which is probably not what you intended. Use this:

const users = [
  {name: 'liam', id: 1}, {name: 'jon', id: 2}
];
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading