Home > front end >  node JS erorr in my app (Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to th
node JS erorr in my app (Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to th

Time:12-01

When I type nodeJS I get this error in my application please help me. , When I run the app it works, when I send the first POST it gives me this error

const express = require('express')
const Workout = require("../models/workoutModel")

const router = express.Router()

// Get all workouts
router.get('/',(req,res) => {
    res.json({mssg:'GET all workouts'})
})

// Get a single workouts
router.get('/:id',(req,res) => {
    res.json({mssg: 'GET a single workout'})
})

// POST a new workout
router.post('/', async (req,res) => {
    const {title,load,reps} = req.body

    try {
        const workout = await Workout.create({title,load,reps})
        res.status(200).json(workout)
    } catch(error) {
        res.status(400).json({error: error.message})
    }
    res.json({mssg: 'POST a new workout'})
})

// DELETE a workout
router.delete('/:id',(req,res) => {
    res.json({mssg: 'DELETE a workout'})
})

// UPDATE a workout
router.patch('/:id',(req,res) => {
    res.json({mssg: 'UPDATE a workout'})
})


module.exports = router

When I run the app it works, when I send the first POST it gives me this error.

CodePudding user response:

you sent response in try-catch, so res.json({mssg: 'POST a new workout'}) cause to error. delete res.json({mssg: 'POST a new workout'}) for solving error.

CodePudding user response:

you sent response twice in the post function

  • Related