app.patch() is not working.get and delete is working but not patch.Is there any coding error what am i doing wrong?

Viewed 1630

I want to create server which can perform CRUD.

Movie model has only 1 property named title.

I am able to create new movie,delete movie and search a movie by its _id.But update is not working.So,I have shown code below

1.GET and DELETE i have tested on postman and working properly.

[As i said get is working][1]

2.PATCH request is not working .

It is not even giving any response and just loading.

localhost:3000/movies/id_of_movie

here id_of_movie is id of movie for update.

const express=require('express');

const  {mongoose}=require('./db/mongoose');

const bodyParser=require('body-parser');

const {Movie}=require('./db/models');

const app=express();

//middleware
app.use(bodyParser.json());
app.use(function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*"); // update to match the domain you will make the request from
    res.header("Access-Control-Allow-Methods", "GET, POST, HEAD, OPTIONS, PUT, PATCH, DELETE"); 
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    next();
  });
/* route handlers */
app.get('/movies',(req,res)=>{
    Movie.find({}).then((movies)=>{
        res.send(movies);
    });
});

app.post('/movies',(req,res)=>{
    let title=req.body.title;

    let newMovie=new Movie({
        title
    });
    newMovie.save().then((movieDoc)=>{
        res.send(movieDoc);
    });
});

app.get('/',( req, res )=>{
    res.send("hello");
});

app.patch('/movies/:id',(req,res)=>{
    console.log(req.body);
    Movie.findByIdAndUpdate({
        _id:req.params.id
    },{
        $set:req.body
    }).then(()=>{
        res.sendStatus({message:"success"});
    });
});

app.delete('/movies/:id',(req,res)=>{
    Movie.findOneAndRemove({
        _id:req.params.id
    }).then((removedMovieDoc)=>{
        res.send(removedMovieDoc);
    });
});
```````````````````````````````````````````````````````


[It is just loading and loading][2]


  [1]: https://i.stack.imgur.com/A6LVa.png
  [2]: https://i.stack.imgur.com/YauA7.png
1 Answers

Your express code looks fine, it could be that your mongoose query runs into an error which you are currently not handling. Node will run into an UnhandledPromiseRejection and the request will hang forever. Add a catch handler to your promise and handle your error, e.g.:

app.patch('/movies/:id',(req,res)=>{
    console.log(req.body);
    Movie.findByIdAndUpdate({
        _id:req.params.id
    },{
        $set:req.body
    }).then(()=>{
        res.sendStatus({message:"success"});
    }).catch(err => {
       res.status(500).send(err.message);
    })
});
Related