Put request with Express and Mongo DB

Issue

I am building a simple react list app that uses express and and mongoDB to get a handle of all CRUD operations. So far I have GET, POST, DELETE, working just fine but I can’t seem to get PUT functioning.
When I attempt a PUT request through Insomnia i get the following error “Error: Failure when receiving data from the peer”

MODELS

const mongoose = require('mongoose');

const Schema = mongoose.Schema;

const listItemSchema = new Schema({
  itemname: { type: String, required: true, unique: true },
  category: { type: String, required: true, unique: true },
}, {
  timestamps: true,
});

const ListItem = mongoose.model('ListItem', listItemSchema);

module.exports = ListItem;

ROUTES

const router = require('express').Router();
let ListItem = require('../models/list.model');

router.get('/', async (req, res) => {
    try {
        const list = await ListItem.find();
        res.json(list);
    } catch(err) {
        console.error(err.message);
        res.send(400).send('Server Error');
    }
});

router.get('/:id', async (req, res) => {
    try {
        const item = await ListItem.findById(req.params.id);
        res.json(item);
    } catch(err) {
        console.error(err.message);
        res.send(400).send('Server Error');
    }
});

router.post('/addlistitem', async (req, res) => {
    try {
        const { itemname, category } = await req.body;
        const newListItem = new ListItem({
            itemname,
            category
          });

          await newListItem.save()
          res.json('ListItem added!')    
    } catch(err) {  
        console.error(err.message);
        res.status(500).json('Server Error');
   }
});


router.delete('/:id', async (req, res) => {
    try {
         await ListItem.findByIdAndDelete(req.params.id);
        res.json(' Item deleted.');

        } catch(err) {
          res.status(400).json('Error: ' + err);
     }
  });

  router.put('/:id', async (req, res) => {
    try {
         await ListItem.findByIdAndUpdate(req.params.id, {
            itemname: req.body.itemname,
            category: req.body.category
        });

    } catch(err) {
        console.error(err.message);
        res.send(400).send('Server Error');
    }
});


module.exports = router;

Solution

You forgot to send response in your put route

  router.put('/:id', async (req, res) => {
    try {
      await ListItem.findByIdAndUpdate(req.params.id, {
          itemname: req.body.itemname,
          category: req.body.category
      });
      // Send response in here
      res.send('Item Updated!');

    } catch(err) {
        console.error(err.message);
        res.send(400).send('Server Error');
    }
});

Answered By – Nisan Co┼čkun

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published