glassraven
glassraven

Reputation: 323

Node.js/ Express DELETE method not working

I'm trying to delete data of a form. GET and PUT methods work but not DELETE. My goal is to change the form POST method with a JS function and then call it with a delete button, so I can erase data. But it's not working. The HTML:

<form id="protest_form" action="scout_post" method="POST">

            <input type="text" id="scoutName" name="scoutName" placeholder="name"> <br>
            <input type="text" id="scoutSurname" name="scoutSurname" placeholder="surname"> <br>
            <input type="text" id="scoutPassword" name="scoutPassword" placeholder="password"> <br>

            <button type="submit" id="button" class="btn btn-primary">Submit</button>
            <button type="button" id="button" class="btn btn-danger" onclick="deleteForm()">Delete</button>
        </form>

The JS function:

function deleteForm() {

        document.getElementById('protest_form').setAttribute("method", "delete");
        document.getElementById('protest_form').submit();

    }

And the Node routings:

app.post('/scout_post', urlencodedParser,function (req,res){

    var name= req.body.scoutName,
        surname=req.body.scoutSurname,
        password=req.body.scoutPassword;


            db.collection('scoutPost').insertOne(
                { 'name': name, 'surname': surname,'password':password},
                function (err, r) {
                    assert.equal(null, err);
                    res.send("Document inserted with _id: " + r.insertedId);
                }
            );  
})

app.delete('/scout_post', urlencodedParser,function (req,res){

        var name= req.body.scoutName,
            surname=req.body.scoutSurname,
            password=req.body.scoutPassword;


                db.collection('scoutPost').remove(
                    { 'name': name, 'surname': surname,'password':password},
                    function (err, r) {
                        assert.equal(null, err);
                        res.send("Document deleted");

                    });

    }) 

When I click on button that calls the deleteForm() function, I get this error:

Cannot GET /scout_post?scoutName=&scoutSurname=&scoutPassword=

And if I change the HTML and Node route to GET method, I get inserted documents, not deleted when clicking the DEL button...How do I fix this? Thanks

Upvotes: 2

Views: 6870

Answers (2)

mscdex
mscdex

Reputation: 106698

Only GET and POST are allowed in HTML forms. If you want to submit a DELETE request, you will have to do so via XHR client-side or by using a method override middleware on the server side and making the appropriate changes on the client side.

Upvotes: 2

ponury-kostek
ponury-kostek

Reputation: 8060

As documentation on MDN say, there is only "POST" and "GET" method available on form method attribute. You need to use AJAX to accomplish this

Upvotes: 0

Related Questions