Search code examples
typescriptcorsfetch

Method DELETE not allowed on Fetch request - CORS


I've had this problem before with another Request, however it kinda just fixed itself. Now I am having the same problem with Delete request, however nothing works. I've tried setting the 'mode: cors', I've tried allowing all origin and even specific hostnames. Nothing seems to work.

The console error: console log error screenshot

The Fetch in my module:

async function deleteProject(_id: string) {
    try {
      const response = await fetch(urlDelete + _id, {
        method: 'DELETE',
        headers: {
          Accept: 'application/json',
          'auth-token': token as string,
        }
      });

      if (!response.ok) {
        throw new Error(`Error! status: ${response.status}`);
      }

      const result = (await response.json()) as GetProjectResponse;
      // @ts-expect-error: Unreachable code error
      state.Project = result;
      return result;
    } catch (error) {
      if (error instanceof Error) {
        console.log('error message: ', error.message);
        return error.message;
      } else {
        console.log('unexpected error: ', error);
        return 'An unexpected error occurred';
      }
    }
  } 

My backend route:

router.delete("/delete/:id", verifyToken, (req, res) => {
    const id = req.params.id;
    project.findByIdAndDelete(id)
    .then(data => {
        if (!data) {
            res.status(404).send({ message: "Cannot delete project with id: " + id});
        } else {
            res.send({ message: "Project was deleted."})
        }
    })
    .catch(err => { res.status(500).send({ message: "Error deleting project with id: " + id }); })
});

Solution

  • Okay, so I went through my backend, and after couple merges I lost some of my headers, so I had to specifically declare all OPTIONS for cors. Thanks everyone for input.