Friday 2 June 2017

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



via glassraven

No comments:

Post a Comment