caged_raven_wings
caged_raven_wings

Reputation: 363

TypeError: Cannot destructure property id of req.params as it is undefined

I'm trying to get a user profile from a database and return it as a json object when the profile url (localhost:3000/Profile/1) is ran. but i am getting this error: TypeError: Cannot destructure property id of req.params as it is undefined.

here is the code in the express server.

const express = require('express');
const bodyParser = require('body-parser');
const bcrypt = require('bcryptjs');
const cors = require('cors');
const knex = require('knex');

const app = express();
app.use(cors());
app.use(bodyParser.json());


app.get('/Profile/:id', (res,req) =>{
    const {id} = req.params;
    db.select('*').from('user').where({id})
    .then(user => {
    res.json(user[0])})
})

i used postman to send the get request.

Upvotes: 2

Views: 10271

Answers (4)

kenTom
kenTom

Reputation: 1

The problem is you haven't passed in the parameters in the get function correctly, I am using next js, I got the same error, Here is how I solved it

export async function GET(req, res) {
    try {

        let { id } = req.query
        console.log('The id is:', id)

    }catch (error) {
        console.error(error);
        return NextResponse.json({message: "Error getting the id", error})
    }
}

I changed above code to

export async function GET(req, { params }) {
    try {
        
        const { id } = params
        console.log('The id is:', id)

    }catch (error) {
        console.error(error);
        return NextResponse.json({message: "Error getting the id", error})
    }
}

Upvotes: -1

Vivek Sengar
Vivek Sengar

Reputation: 46

You passing the wrong parameters to the get function

E.g.

// respond with "hello world" when a GET request is made to the homepage
app.get('/', function (req, res) {
  res.send('hello world')
})

In your case

app.get('/Profile/:id', (req, res) =>{
   console.log(req.params)
}

Upvotes: 3

José Salina
José Salina

Reputation: 148

I see your error man, you put in the function (res, res) and should be (req,res).

Upvotes: 3

JuanDa237
JuanDa237

Reputation: 376

The order of parameters is Request, Response so you have to do this:

app.get('/profile/:id', (request, response) => {
    const { id } = request.params;
    db.select('*').from('user').where({id}).then(
       user => {
           res.json(user[0])
       });
});

Upvotes: 1

Related Questions