Skip to content
Advertisement

Node.js getting Uncaught error: invalid input syntax for type integer: “NaN”

I am very new to JS and I’m trying to create an API using node.js however I’m getting the error:

Uncaught error: invalid input syntax for type integer: "NaN"

The requests are fine when I do a GET and POST request but I’m having trouble with the PUT and DELETE. I get the same error with both requests. Here is my code:

    const getProfiles = (request, response) => {
  pool.query('SELECT * FROM profiles', (error, results) => {
    if (error) {
      throw error
    }
    response.status(200).json(results.rows)
  })
}

const addProfiles = (request, response) => {
  const {name, bio} = request.body

  pool.query(
    'INSERT INTO profiles (name, bio) VALUES ($1, $2) RETURNING id',
    [name, bio],
    (error) => {
      if (error) {
        throw error
      }
      response.status(201).json({status: 'success', message: 'Profile added.'})
    })
    
  }

const updateProfiles = (request, response) => {
  const id = parseInt(request.params.id)
  const {name, bio} = request.body

  pool.query(
    'UPDATE profiles SET name = $1, bio = $2 WHERE id = $3 RETURNING id',
    [name, bio, id],
    (error) => {
      if (error) {
        throw error
      }
      response.status(202).json({status: 'success', message: 'Profile updated with ID: ${id}'})
    })
}

const deleteProfiles = (request, response) => {
  const id = parseInt(request.params.id)

  pool.query(
    'DELETE FROM profiles WHERE id = $1', [id],
    (error, results) => {
      if (error) {
        throw error
      }
    response.status(203).send(`Profile deleted with ID: ${id}`) 
  })
}

app
  .route('/profiles')
  // GET endpoint
  .get(getProfiles)
  // POST endpoint
  .post(addProfiles)
  //UPDATE endpoint
  .put(updateProfiles)
  // DELETE endpoint
  .delete(deleteProfiles)

  

// Start server
app.listen(process.env.PORT || 3002, () => {
  console.log(`Server listening`)
})

I am very much new to this and if you spot where I went wrong I would very much appreciate and explanation for me to better understand it and never make this mistake again. Thank you.

Advertisement

Answer

As far as I can see, req.params.id is undefined, because you are not telling express that route should receive a param.

Change this:

app
  .route('/profiles')
  // GET endpoint
  .get(getProfiles)
  // POST endpoint
  .post(addProfiles)
  //UPDATE endpoint
  .put(updateProfiles)
  // DELETE endpoint
  .delete(deleteProfiles)

To this:

app
  .route('/profiles')
  // GET endpoint
  .get(getProfiles)
  // POST endpoint
  .post(addProfiles)

app
  .route('/profiles/:id')  // :id means we are expecting that param
  //UPDATE endpoint
  .put(updateProfiles)
  // DELETE endpoint
  .delete(deleteProfiles)

And when you do the PUT or DELETE request, the endpoint should look like this: /profiles/

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement