1

I am recieving this error: Cannot set headers after they are sent to the client

I take that to mean the code is attempting to set the response headers more than once. This is the code, but I cant seem to find out where the headers are being set twice.

async function createTrip(request, response) {
    const { vehicleId, driverId, startedAt, expectedReturn } = request.body
    let driver, vehicle
    //validation
    await pool.query(
        'SELECT * FROM Vehicle WHERE id = $1',
        [vehicleId],
        (error, results) => {
            if (error) {
                throw `ERROR::createTrip threw an error: ${error}`
            }
            if (results.rowCount === 0) {
                return response.send({ status: 404, message: `vehicle with id ${vehicleId} does not exist.` })
            } else if (results.rows[0].in_use) {
                return response.send(403).send({ status: 403, message: `vehicle with id ${vehicleId} is not available for rental` })
            } else {
                vehicle = results.rows[0]
            }
        }
    )
    await pool.query(
        'SELECT * FROM Driver WHERE id = $1',
        [driverId],
        (error, results) => {
            if (error) {
                throw new Error(`ERROR::createTrip threw an error: ${error}`)
            } else if (results.rowCount === 0) {
                return response.status(404).send({ status: 404, message: `driver with id ${driverId} does not exist` })
            } else {
                driver = results.rows[0]
            }
        }
    )

    //event
    await pool.query(
        'INSERT INTO Trip (status,started_at, expected_return, driver, vehicle) VALUES ($1,$2,$3,$4,$5) RETURNING *',
        ['active', startedAt, expectedReturn, driverId, vehicleId],
        (error, results) => {
            if (error) {
                throw `ERROR::createTrip threw an error: ${error}`
            } else {
                return response.status(200).send({ id: results.rows[0].id, status: results.rows[0].status, startedAt, expectedReturn, driver, vehicle })
            }
        }
    )
    await pool.query(
        'UPDATE Vehicle SET in_use = TRUE WHERE id = $1',
        [vehicleId],
        (error) =>{
            if(error){
                throw `ERROR::createTrip threw an error: ${error}`
            }
        }
    )
}

1 Answers1

0

Your createTrip function does four queries. Each of those queries results in a response potentially being called. You should do all the processing from all the queries you need to inside a try/catch block. Then, instead of sending a response when rowCount === 0 for example, throw an error, catch it in the catch block and send the response from there.

Tyler2P
  • 2,324
  • 26
  • 22
  • 31
joshnishikawa
  • 71
  • 1
  • 5