Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

275
Vistas
Express/node.js debugging error: can't set headers after they are sent

I'm trying to create a basic CRUD application and facing trouble while debugging. To build my CRUD application, I'm currently using node.js, express, and mongodb. Any help that you all could provide would be really really helpful.

context: for reference I'm using this:

https://zellwk.com/blog/crud-express-mongodb/, currently on "Showing quotes to users" 

my problem: i'm getting the following error with my code and i'm not sure if this is due to the placement of my code.

Error: Can't set headers after they are sent.
    at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:357:11)
    at ServerResponse.header (C:\Users\hcqph\gitprojects\crudbeta\node_modules\express\lib\response.js:725:10)
    at ServerResponse.contentType (C:\Users\hcqph\gitprojects\crudbeta\node_modules\express\lib\response.js:558:15)
    at ServerResponse.send (C:\Users\hcqph\gitprojects\crudbeta\node_modules\express\lib\response.js:145:14)
    at done (C:\Users\hcqph\gitprojects\crudbeta\node_modules\express\lib\response.js:962:10)
    at tryHandleCache (C:\Users\hcqph\gitprojects\crudbeta\node_modules\ejs\lib\ejs.js:208:10)
    at View.exports.renderFile [as engine] (C:\Users\hcqph\gitprojects\crudbeta\node_modules\ejs\lib\ejs.js:412:10)
    at View.render (C:\Users\hcqph\gitprojects\crudbeta\node_modules\express\lib\view.js:128:8)
    at tryRender (C:\Users\hcqph\gitprojects\crudbeta\node_modules\express\lib\application.js:640:10)
    at EventEmitter.render (C:\Users\hcqph\gitprojects\crudbeta\node_modules\express\lib\application.js:592:3)

this is my code:

app.use(bodyParser.urlencoded({extended: true}))

//set 'ejs' template engine, and default extension is ejs
app.set('view engine', 'ejs')

/* -------- for team documentation --------
=> = replacement for function

app.get hand a GET request (read operation)
------------------------------------------------ */
app.get('/', (req, res) => {
    //serves index.html back to browser
    res.sendFile(__dirname + '/index.html')

    //gets list of trips from mlab.com
    var cursor = db.collection('trips').find()

    //retrieves list of trips retrieved from mlab
    db.collection('trips').find().toArray(function(err, results) {
        if(err) return console.log(err)

        //renders index.ejs
        res.render('index.ejs', {trips:results})
    })
})



/* app.post handles a create request */
app.post('/trips', (req, res) => {
    db.collection('trips').save(req.body, (err, result) =>{
        if (err) return console.log(err)

        console.log('saved to database')
        res.redirect('/') //causes browser to reload
    })
})

is it because of where i'm playing my app.set? how can i fix this?

in addition, am i referencing my res.render for index.ejs properly if it's nested within folder views?

about 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

You cannot send two responses for one request

remove one of the lines of your code:

EITHER

  • res.sendFile(__dirname + '/index.html')

OR

  • res.render('index.ejs', {trips:results})

What's happening in your code:

When / get request is fired node redirects you to index.html file but the next executes simultaneously and renders to index.ejs file which results in error because the node has already sent response now it cannot send headers in response to previous requests again.

So you have remove one of lines above mentioned.

about 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda