cphill
cphill

Reputation: 5914

NodeJS - jQuery DELETE Method

I am trying to send a DELETE request on a button click, but I'm not sure if my jQuery is set up and despite using routing that is for the delete method, I am still getting GET request errors Cannot GET /app/delete/1. Am I on the right track with my jQuery and how do I prevent this GET request?

Route:

appRoutes.route('app/delete/:testId')

    .delete(function(req, res){
        models.Test.destroy({
            where: {
                userId: req.user.user_id,
                testId: req.params.testId           
            }
        }).then(function(){
            res.redirect('/app');
        });
    });

Link:

<a href="/app/delete/{{test.testId}}" id="test-delete-link">Delete</a>

jQuery:

<script type="text/javascript">
        $(document).ready(function() {
            $('#test-delete-link').click(function(){
                $.ajax({
                    type: 'DELETE',
                    url: '/app/delete/{{test.testId}}'
                });
            });
        });
    </script>

Upvotes: 0

Views: 1363

Answers (1)

afuous
afuous

Reputation: 1498

The issue is that when a link is clicked, it uses GET. When your link is clicked, two things are happening.

  • The click event is triggered and jQuery sends the DELETE request.
  • The browser sends a GET request to the same path because it is a link.

To fix this, set the href property of the link to "javascript:void(0);". This makes it so that clicking the link does nothing except what is specified in the click event.

As a side note, I would change the path of the request from /app/delete/:testId to /app/:testId. The way it is right now is redundant, as you are saying DELETE /app/delete/1. The more RESTful way to do it is DELETE /app/1.

Upvotes: 5

Related Questions