I created a server on express.js and when I try to process 404 errors, I get an error:
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client Here is my code in which the error
router.get('/:productId',(req,res,next) => { const id = req.params.productId; Product.findById(id) .exec(doc => { if (doc) { res.status(200).json({ doc }) } else { res.status(404).json({ message:"Invalid id" }) } }) .then(doc => { console.log(doc) }) .catch(err => { console.log(err) res.status(500).json({ error: err }) }) }) Tell me where I am wrong and how to correct the error. Please :)
Full code
const express = require('express') const router = express.Router() const mongoose = require('mongoose') const Product = require('../models/products') router.get('/',(req,res,next) => { res.status(200).json({ message : 'Request' }) }) router.post('/',(req,res,next) => { const product = new Product({ _id: new mongoose.Types.ObjectId(), name: req.body.name, price: req.body.price }) product.save() .then((res) => { console.log(res) res.status(201).json({ message : 'Request', createdProduct : res }) } ) .catch(err => {console.log(err) res.status(500).json({ error: err })} ) }) router.get('/:productId',(req,res,next) => { const id = req.params.productId; Product.findById(id) .exec(doc => { if (doc) { res.status(200).json(doc) } else { res.status(404).json({ message:"Invalid id" }) } }) .then(doc => { console.log(doc) }) .catch(err => { console.log(err) res.status(500).json({ error: err }) }) }) router.patch('/:productId',(req,res,next) => { const id = req.params.productId; if (id === 'special'){ res.status(200).json({ message : 'special', id : id }) }else{ res.status(200).json({ message : 'not special' }) } }) router.delete('/:productId',(req,res,next) => { const id = req.params.productId; if (id === 'special'){ res.status(200).json({ message : 'special', id : id }) }else{ res.status(200).json({ message : 'not special' }) } }) module.exports = router So changed
router.get('/:productId',(req,res,next) => { const id = req.params.productId ObjectId = mongoose.Types.ObjectId if (!ObjectId.isValid(id)) { res.status(404).json({ message: 'Invalid id!' }) } else { Product.findById(id) .exec(doc => { if ( doc ) { console.log(doc) res.status(200).json(doc) } else { res.status(404).json({ message: 'Not found!' }) } }) } })
404, and then500. Try to put.exec(doc => {at the end of the function.exec(doc => {:res.end();- Dmitry Miroshnichenkoexecandthen.catch? use one thing - uber42.json({ doc })? I'm talking about curly braces. - Suvitruf ♦{ "message": "Not found!" }{ "message": "Not found!" }- Oleksandr Tatarinov