Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

279
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda