I am having trouble deleting items from the front end to the mongodb atlas database. I need to fix this problem please
Thanks
router.delete('/api/bookings/:id', async (req, res) => {
const { id } = req.params; // Obtén el ID desde la URL
try {
// Convierte el ID en ObjectId para asegurar que esté en el formato correcto
const result = await Booking.deleteOne({ _id: mongoose.Types.ObjectId(id) });
// Verifica si realmente se eliminó una reserva
if (result.deletedCount === 0) {
return res.status(404).json({ message: 'Reserva no encontrada' });
}
res.json({ message: 'Reserva eliminada con éxito' });
} catch (err) {
console.error(err);
res.status(500).json({ message: 'Error al eliminar la reserva' });
}
});
THE CODE FRONT FOR DELETE IS THIS
const handleDelete = async (id) => {
const confirmDelete = window.confirm('¿Estás seguro de que quieres eliminar esta reserva?');
if (!confirmDelete) return;
try {
const response = await fetch(`https://api-party-kids.vercel.app/api/bookings/${id}`, {
method: 'DELETE',
headers: {
'Content-Type': 'application/json',
},
});
if (!response.ok) {
const data = await response.json();
throw new Error(data.message || 'Error eliminando la reserva');
}
// Si la eliminación es exitosa, actualizar el estado eliminando la reserva
setBookings(prevBookings => prevBookings.filter(booking => booking._id !== id));
alert('Reserva eliminada con éxito');
} catch (error) {
console.error('Error eliminando la reserva:', error);
alert('Hubo un error al intentar eliminar la reserva');
}
};
POST AND GET WORK WITHOUT PROBLEM. I CAN CREATE RESERVATIONS WITHOUT PROBLEM. THE PROBLEM IS WHEN I WANT TO DELETE AN ITEM
Access to fetch at 'https://api-party-kids.vercel.app/api/bookings/676eac7942b3d96287ba4d08' from origin 'https://front-party-kids.vercel.app' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: 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.Entender este errorAI
index-inPmOciP.js:87
DELETE https://api-party-kids.vercel.app/api/bookings/676eac7942b3d96287ba4d08 net::ERR_FAILED
h @ index-inPmOciP.js:87
onClick @ index-inPmOciP.js:87
xe @ index-inPmOciP.js:37
ot @ index-inPmOciP.js:37
tt @ index-inPmOciP.js:37
Xp @ index-inPmOciP.js:37
Gp @ index-inPmOciP.js:37
(anónimo) @ index-inPmOciP.js:37
Yf @ index-inPmOciP.js:40
ke @ index-inPmOciP.js:37
Vc @ index-inPmOciP.js:37
Pc @ index-inPmOciP.js:37
y_ @ index-inPmOciP.js:37Entender este errorAI
index-inPmOciP.js:87 Error eliminando la reserva: TypeError: Failed to fetch
at h (index-inPmOciP.js:87:22853)
at onClick (index-inPmOciP.js:87:24473)
at Object.xe (index-inPmOciP.js:37:9835)
at ot (index-inPmOciP.js:37:9989)
at tt (index-inPmOciP.js:37:10046)
at Xp (index-inPmOciP.js:37:31379)
at Gp (index-inPmOciP.js:37:31796)
at index-inPmOciP.js:37:36864
at Yf (index-inPmOciP.js:40:36981)
at ke (index-inPmOciP.js:37:8972)
overrideMethod @ hook.js:608
h @ index-inPmOciP.js:87
await in h
onClick @ index-inPmOciP.js:87
xe @ index-inPmOciP.js:37
ot @ index-inPmOciP.js:37
tt @ index-inPmOciP.js:37
Xp @ index-inPmOciP.js:37
Gp @ index-inPmOciP.js:37
(anónimo) @ index-inPmOciP.js:37
Yf @ index-inPmOciP.js:40
ke @ index-inPmOciP.js:37
Vc @ index-inPmOciP.js:37
Pc @ index-inPmOciP.js:37
y_ @ index-inPmOciP.js:37Entender este errorAI
index-inPmOciP.js:87 Obtener no ha podido cargar: DELETE "https://api-party-kids.vercel.app/api/bookings/676eac7942b3d96287ba4d08".
I THINK THE CORS CONFIGURATION IS CORRECT SINCE I HAVE THE METHODS AND OPTIONS
MY server.js is this
'use strict'
const express = require('express');
const dotenv = require('dotenv');
const cors = require('cors');
const connectDB = require('./config/db');
const bookingRoutes = require('./routes/bookingRoutes');
// Cargar variables de entorno
dotenv.config();
// Conectar a la base de datos
connectDB();
// Inicializar la app de Express
const app = express();
// Configuración de CORS
const corsOptions = {
origin: 'https://front-party-kids.vercel.app', // La URL de tu frontend en Vercel
methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS', 'PATCH'], // Métodos permitidos
allowedHeaders: ['Content-Type', 'Authorization', 'X-Requested-With'], // Cabeceras permitidas
optionsSuccessStatus: 204, // Opcional para manejar preflight exitoso
};
// Aplica CORS a toda la aplicación
app.use(cors(corsOptions));
// Middleware para manejar las preflight requests (OPTIONS)
// Middleware para analizar datos JSON
app.use(express.json());
// Rutas de la API
app.use('/api/bookings', bookingRoutes);
// Exportar la app para que Vercel la maneje
module.exports = app;
@NeNaD If you need more information, just ask me. I have front and back spread out in vercel for now.
Hi @Juani_Gnacio,
Based on the error message, the issue is related to CORS.
Just to be sure if it’s CORS or not, can you change your logic to integrate CORS without custom configs, and check if that would work:
app.use(cors());
I am not a Vercel expert, but it’s also possible that something has to be configured on the Vercel level for CORS to run properly.
Other than that, your backend code seems valid.
1 Like