2

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.

DELETE /campgrounds/6326c2be5c60486aeb479eab 302
DELETE /campgrounds 404
GET /campgrounds/6326c2be5c60486aeb479eab 500

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.

enter image description here

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);
            });
    });
});
Aryan3212
  • 121
  • 2
  • 9
  • You have to show us how you make a request and how do you follow the redirect. – Konrad Sep 19 '22 at 16:52
  • I added a few code snippets, hope that helps. – Aryan3212 Sep 20 '22 at 06:06
  • 2
    [Please do not upload images of code/errors when asking a question](https://meta.stackoverflow.com/q/285551). See also [How do I ask a good question?](https://stackoverflow.com/help/how-to-ask) and [How to create a Minimal, Reproducible Example](https://stackoverflow.com/help/minimal-reproducible-example) from the help centre. – Phil Sep 20 '22 at 06:16
  • @Phil I apologize and thank you for the links. – Aryan3212 Sep 20 '22 at 06:18
  • https://stackoverflow.com/questions/14598703/rails-redirect-after-delete-using-delete-instead-of-get . This post seems to answer my question. DELETE requests seem to be handled differently by the browser and AJAX. – Aryan3212 Sep 20 '22 at 07:55

0 Answers0