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