'blocked by CORS policy Method PATCH is not allowed

im tryng build crud app using MERN stack, method add and get not got blocked by cors, but patch method got blocked by cors alredy install cors module on my server and still didnt work

routes

import express from 'express';
import { createPost, getPost, updatePost } from '../controllers/posts.js';

const router = express.Router();

router.get('/', getPost);
router.post('/', createPost);
router.patch('/:id', updatePost);

export default router;


server/controllers

export const updatePost = async (req, res) => {
  const { id: _id } = req.params;
  const post = req.body;
  if (!mongoose.Types.ObjectId.isValid(id))
    return res.status(404).send(`no post with id ${id}`);
  const updatedPost = postMessage.findByIdAndUpdate(_id, post, { new: true });
  res.json(updatedPost);
};


client>src>api
import axios from 'axios';

const url = 'http://localhost:3001/posts';

export const fetchPosts = () => axios.get(url);
export const createPost = (newPost) => axios.post(url, newPost);
export const updatePost = (id, updatePost) =>
  axios.patch(`${url}/${id}`, updatePost);



Solution 1:[1]

Certain CORS requests are considered ‘complex’ and require an initial OPTIONS request (called the “pre-flight request”)

If you are making requests other than GET/HEAD/POST (such as PATCH) you need to enable pre-flight request

Serverside add these lines app.options('/posts/:id', cors()) // enable pre-flight request

Source - [ExpressJs Docs][1]

[1]: https://expressjs.com/en/resources/middleware/cors.html#:~:text=on%20port%2080%27)%0A%7D)-,Enabling%20CORS%20Pre%2DFlight,-Certain%20CORS%20requests

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 sai vineeth