How to enable delete request for nodejs with cors

I am working on a MERN stack app and when ever I send a delete request to my server using fetch api I get a cors error.

"Access to fetch at 'http://localhost:5000/api/users/delete-user' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled."

I have tried every solution for the problem here but nothing seems to work for me. Here is my code

import express from 'express';
import mongoose from 'mongoose'
import cors from 'cors';
import productRoutes from './api/product-api.js';
import orderRoutes from './api/order-api.js';
import eventRoutes from './api/event-api.js';
import tutorRoutes from './api/tutor-api.js';
import assignmentRoutes from './api/assignment-api.js';
import userRoutes from './api/user-api.js';
import accomodationRoutes from './api/accomodation-api.js';

const app  = express();
const  PORT = process.env.PORT || 5000


// Middleware goes here!!!!

app.use(express.json());
app.use(cors());



// Connecting to database

mongoose.connect('mongodb://localhost:27017/hitstore', (err)=>{

    if(err){
        console.log("Could not connect to db");
    } else {
        console.log("Connected to the db");
        app.listen(PORT, () => console.log(`http://localhost:${PORT}`))
    }
})


// Routes

app.get('/', (req,res)=>{
    res.json({message: "Hit store api"})
})


// routes middleware

app.use('/api/products', productRoutes);
app.use('/api/orders', orderRoutes);
app.use('/api/events', eventRoutes);
app.use('/api/assignments', assignmentRoutes);
app.use('/api/tutors', tutorRoutes);
app.use('/api/users', userRoutes);
app.use('/api/accomodations', accomodationRoutes);

Here is the code for my frontend

 fetch(`${backendUrl}/api/users/delete-user`, {
            method: "DELETE",
            headers: {"Content-Type": "application/json", "Authorization": localToken},
            body: JSON.stringify(userID),
        })
        .then(res => res.json())
        .then(result => {
            console.log(result)
        })
        .catch((err) => {
            console.log("Could not send request\nErr: " + err);
        })

Upvotes: 1

Views: 1993

Answers (1)

jub0bs
jub0bs

Reputation: 66244

The default configuration (which you are using) of Express's CORS middleware allows the DELETE method:

{
  "origin": "*",
  "methods": "GET,HEAD,PUT,PATCH,POST,DELETE",
  "preflightContinue": false,
  "optionsSuccessStatus": 204
}

No problem there. However,

you need to also explicitly allow those headers:

const corsOptions = {
  allowedHeaders: ['Content-Type', 'Authorization']
};
app.use(cors(corsOptions));

Upvotes: 3

Related Questions