使用锚标记覆盖nodeJS中的方法GET to DELETE

Nor*_*ali 4 javascript node.js express

所以,我想我在我的ejs文件中有这个链接:

<a href="/user/12">Delete</a>
Run Code Online (Sandbox Code Playgroud)

在我的路线文件中,我删除了如下代码:

router.delete( '/user/:id', function ( req, res ) {
   // delete operation stuff
});
Run Code Online (Sandbox Code Playgroud)

所以我的问题是,我如何覆盖GET从链接到DELETE方法的请求,以确保我的router.delete路由能够处理它.现在,它只检测到一个请求GET.我正在使用此方法覆盖模块来处理它,但似乎所有示例都使用表单元素,而不是锚定方式.任何人?

Nor*_*ali 6

无论如何,现在这里是我用来在应用程序请求之前使用覆盖GET请求的解决方案middleware,到目前为止链接我改变它href看起来像这样:

<a href="/user/12?_method=DELETE" >Delete</a>
Run Code Online (Sandbox Code Playgroud)

在途中:

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(); 
});
Run Code Online (Sandbox Code Playgroud)

最后,请求的路径将匹配此路由:

router.delete( '/user/:id', function ( req, res ) {
  // delete operation stuff
});
Run Code Online (Sandbox Code Playgroud)

任何遇到这些问题的人都可以尝试一下,如果有人遇到这个问题并且能够通过很好的解决方案解决它,请告诉我.快乐的编码!