node.js Express.js 在控制器中获取 http 方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11168115/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Express.js get http method in controller
提问by dev.pus
I am building a registration form (passport-local as authentication, forms as form helper).
我正在构建一个注册表(passport-local 作为身份验证,表单作为表单助手)。
Because the registration only knows GET and POST I would like to do the whole handling in one function.
因为注册只知道 GET 和 POST 我想在一个函数中完成整个处理。
With other words I am searching after something like:
换句话说,我正在寻找类似的东西:
exports.register = function(req, res){
if (req.isPost) {
// do form handling
}
res.render('user/registration.html.swig', { form: form.toHTML() });
};
回答by dev.pus
The answer was quite easy
答案很简单
exports.register = function(req, res) {
if (req.method == "POST") {
// do form handling
}
res.render('user/registration.html.swig', { form: form.toHTML() });
};
But I searched a long time for this approach in the express guide.
但是我在快速指南中搜索了很长时间的这种方法。
Finally the node documentation has such detailed information: http://nodejs.org/api/http.html#http_http_request_options_callback
最后节点文档有这样详细的信息:http: //nodejs.org/api/http.html#http_http_request_options_callback
回答by zkmoonea
Now you can use a package in npm => "method-override", which provides a middle-ware layer that overrides the "req.method" property.
现在你可以在 npm => "method-override" 中使用一个包,它提供了一个覆盖 "req.method" 属性的中间件层。
Basically your client can send a POST request with a modified "req.method", something like /registration/passportID?_method=PUT.
基本上,您的客户端可以使用修改后的“req.method”发送 POST 请求,例如/registration/passportID?_method=PUT.
The
这
?_method=XXXXX
?_方法=XXXX
portion is for the middle-ware to identify that this is an undercover PUT request.
部分用于中间件识别这是一个卧底 PUT 请求。
The flow is that the client sends a POST req with data to your server side, and the middle-ware translates the req and run the corresponding "app.put..." route.
流程是客户端向您的服务器端发送带有数据的 POST 请求,中间件转换请求并运行相应的“app.put...”路由。
I think this is a way of compromise. For more info: method-override
我认为这是一种妥协的方式。欲了解更多信息:方法覆盖

