0

I don't know why this doesn't work, I took it from a tutorial which works! but here's my app.js

const express = require('express')
const mongoose = require('mongoose')
const Todo = require('./models/todo')

const app = express()

mongoose.connect('mongodb+srv://root:xxx@clusterxxx.mongodb.net/xxx?retryWrites=true&w=majority',{useNewUrlParser:true,useUnifiedTopology:true})
const db = mongoose.connection
db.on('error', (error) => console.error(error))
db.once('open', () => app.listen(5000))

app.use(express.urlencoded({extended: false}))
app.set('view engine', 'ejs')

app.get('/', async (req, res) => {
    const todos = await Todo.find()
    res.render('index', {todos: todos})
})

app.post('/create', async (req, res) => {
    res.send('thanks')
    let todo = new Todo({
        title: req.body.todo
    })

    try {
        todo = await todo.save()
        res.redirect('/')
    } catch (err) {
        console.log(err)
    }
})

When I create something, I got redirected to /create and I can see "thanks", but then I don't get redirected to home and the error is thrown:

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

Kokos98c
  • 25
  • 3

1 Answers1

1

You send a body:

res.send('thanks')

and then try to send a header:

res.redirect('/')

That initial send already sent through the headers for a 200 response; you can't change them after that.

Joe
  • 29,416
  • 12
  • 68
  • 88