I have a Node.js app on top of Express and I wanted to redirect to another route after handling a DELETE request. The DELETE request was done through AJAX from a page that was rendered by the server.
Now, I know that I can I have workarounds by using window.location.href
but I still get a extra call from the server as shown in the image below.
The behaviour I was expecting was that calling res.redirect()
on my backend would just redirect to the specified URL as it does so when submitting a form to the backend. So if the form POSTS the data, the backend does a GET request to redirect.
On the other hand, If I do an AJAX POST request I do get a redirect to a GET route.
So, the difference here is AJAX: POST->GET(redirect), AJAX: DELETE->DELETE(redirect). Why are form and AJAX submissions different and why do AJAX POST requests lead to a GET Request while a DELETE request has another DELETE redirect.
Server Side Handlers:
DELETE
const deleteCampground = async (req, res) => {
const { id } = req.params;
const deletingCamp = await CampgroundModel.deleteOne({ _id: id });
res.redirect(`/campgrounds`);
};
POST
const createCampground = async (req, res) => {
const { title, price, description, longitude, latitude, name } = req.body;
const newCamp = new CampgroundModel({
title: title,
price: price,
description: description,
location: {
geometry: {
coordinates: [longitude, latitude],
},
properties: {
name: name || "",
},
},
});
await newCamp.save();
res.redirect(`/campgrounds/${newCamp.id}`);
};
Client side:
AJAX DELETE
function del(e) {
//! This function is attached to onclick on a button
fetch(e.value, { method: "DELETE" })
.then((res) => {
//! Makes a redirect DELETE request where
//! a GET is expected
console.info(res);
})
.catch((e) => console.info(e));
}
AJAX POST
//! This does an AJAX POST request
//! and does an additional GET redirect request
//! this differs from the DELETE request which prompts
//! another DELETE redirect
document.addEventListener("DOMContentLoaded", () => {
const f = document.querySelector("form");
f.addEventListener("submit", (e) => {
e.preventDefault();
console.dir(e.target);
const data = JSON.stringify({
title: "title",
price: 99,
description: "Description",
location: {
geometry: { coordinates: [1, 1] },
properties: { name: "name" },
},
});
console.log(data);
fetch("/campgrounds", {
method: "POST",
headers: {
"Content-type": "application/json",
},
body: data,
})
.then((res) => {
console.log(res);
// window.location.href = r.url;
})
.catch((e) => {
console.log("Catch", e);
});
});
});