如何将中间件放在Node.js / Express.js中的自己的文件中 [英] How to put middleware in it's own file in Node.js / Express.js
问题描述
我是整个Node.js的新东西,所以我仍然试图找到连接的方式。
我正在尝试使用 express-form 验证。根据文档,您可以执行
app.post('/ user',// Route
form(/ /表单过滤器和验证中间件
过滤器(username)。trim()
),
// Express请求处理程序获取过滤和验证数据
函数(req,res){
if(!req.form.isValid){
//处理错误
console.log(req.form.errors);
} else {
//或者,使用窗体对象中过滤的表单数据:
console.log(用户名:,req.form.username);
}
}
);
在App.js.但是,如果我把一些类似 app.get('/ user',user.index);
的东西放在一个单独的文件中。我想要使用验证中间件(或将验证代码放在控制器中),使App.js文件在开始添加更多页面后更容易概述。
基本上我想把一些类似 app.get('/ user',validation .user,user.index);
这是你定义路由的方式: p>
routes.js:
模块。 export = function(app){
app.get(route1,function(req,res){...})
app.get(route2,function(req,res) ...})
}
这是你如何定义你的中间件:
middlewares.js:
module.exports = {
formHandler:function(req,res,next){...}
}
app.js:
//添加您的middlewa res:
middlewares = require(middlewares);
app.use(middlewares.formHandler);
app.use(middlewares ...);
//初始化路线:
require(routes)(app)
另一种方式是使用您的中间件每条路线:
routes.js:
middlewares = require(middlewares)
module.exports = function(app){
app .get(route1,middlewares.formHandler,function(req,res){...})
app.get(route2,function(req,res){...})
}
我希望我回答你的问题。
I am new to the whole Node.js thing, so I am still trying to get the hang of how things "connect".
I am trying to use the express-form validation. As per the docs you can do
app.post( '/user', // Route
form( // Form filter and validation middleware
filter("username").trim()
),
// Express request-handler gets filtered and validated data
function(req, res){
if (!req.form.isValid) {
// Handle errors
console.log(req.form.errors);
} else {
// Or, use filtered form data from the form object:
console.log("Username:", req.form.username);
}
}
);
In App.js. However if I put something like app.get('/user', user.index);
I can put the controller code in a separate file. I would like to do the same with the validation middleware (or put the validation code in the controller) to make the App.js file easier to overview once I start adding more pages.
Is there a way to accomplish this?
Basically I would like to put something like app.get('/user', validation.user, user.index);
This is how you define your routes:
routes.js:
module.exports = function(app){
app.get("route1", function(req,res){...})
app.get("route2", function(req,res){...})
}
This is how you define your middlewares:
middlewares.js:
module.exports = {
formHandler: function(req, res, next){...}
}
app.js:
// Add your middlewares:
middlewares = require("middlewares");
app.use(middlewares.formHandler);
app.use(middlewares...);
// Initialize your routes:
require("routes")(app)
Another way would be to use your middleware per route:
routes.js:
middlewares = require("middlewares")
module.exports = function(app){
app.get("route1", middlewares.formHandler, function(req,res){...})
app.get("route2", function(req,res){...})
}
I hope I answer your questions.
这篇关于如何将中间件放在Node.js / Express.js中的自己的文件中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!