最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Override method GET to DELETE in nodeJS using anchor tag - Stack Overflow

programmeradmin2浏览0评论

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?

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?

Share edited Jan 21, 2016 at 16:50 Norlihazmey Ghazali asked Jan 21, 2016 at 14:48 Norlihazmey GhazaliNorlihazmey Ghazali 9,0601 gold badge25 silver badges42 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 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!

发布评论

评论列表(0)

  1. 暂无评论