2016-01-21 89 views
3

所以的NodeJS爲DELETE,假設我在我的EJS文件鏈接:覆蓋GET方法,使用錨標記

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

而在我的路由文件,我已經刪除代碼類似以下內容:

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

所以我的問題是,我怎麼可以覆蓋GET請求鏈接到DELETE方法,以確保我的router.delete路線能夠處理它。目前,它只能檢測到請求爲GET。我使用這個Method Override模塊來處理它,但似乎所有的例子都是使用form元素,而不是錨點的方式。任何人?

回答

5

不管怎麼說,現在這裏是我以前使用middleware作出申請請求之前重寫GET要求的解決方案,到目前爲止的鏈接我改變href看起來像這樣:

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

而且在路線:

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(); 
}); 

最後,請求的路徑將匹配這條航線:

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

任何遇到此問題的人都可以嘗試一下,如果有人遇到這個問題並且能夠用極好的解決方案解決問題,請告訴我。快樂編碼!

+1

你先生讓我的早晨不那麼沮喪。謝謝! – jeremytripp