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

Time:06-25

"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.

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

CodePudding user response:

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

CodePudding user response:

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

  • Related