【问题标题】:node JS erorr in my app (Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client)node JS erorr in my app (Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client)
【发布时间】:2022-12-01 20:13:19
【问题描述】:

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.

【问题讨论】:

    标签: javascript node.js reactjs express


    【解决方案1】:

    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.

    【讨论】:

      【解决方案2】:

      you sent response twice in the post function

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-09-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-08-16
        相关资源
        最近更新 更多