8

So, supposed i have this link in my ejs file :

<a href="/user/12">Delete</a>

And in my route file, i have delete code like following :

router.delete( '/user/:id', function ( req, res ) {
   // delete operation stuff
});

So my question is, how i can override GET request from link into DELETE method to ensure my router.delete route able to handle it. Right now, its only detect the request as a GET. I'm using this Method Override module to handle it, But seems like all of examples were using form element, not the anchor way. Anyone?

1 Answer 1

9

Anyway, right now here is the solutions i used to override GET request by using middleware before application request was made, so far for the link i change the href to look like this :

<a href="/user/12?_method=DELETE" >Delete</a>

And in route :

router.use( function( req, res, next ) {
    // this middleware will call for each requested
    // and we checked for the requested query properties
    // if _method was existed
    // then we know, clients need to call DELETE request instead
    if ( req.query._method == 'DELETE' ) {
        // change the original METHOD
        // into DELETE method
        req.method = 'DELETE';
        // and set requested url to /user/12
        req.url = req.path;
    }       
    next(); 
});

Finally, the requested path will match this route :

router.delete( '/user/:id', function ( req, res ) {
  // delete operation stuff
});

Anyone who encountered this problems may try it out and if anyone who facing this problems and able to solved it with great solutions, please let me know. Happy codding!

1
  • 1
    You sir have made my morning a little less frustrating. Thanks! Nov 19, 2016 at 18:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.