简化如何调用这个node.js函数
我正在使用node.js restify。
下面的代码工作正常。
var server = restify.createServer({ name: 'myapp', version: '1.0.0' }); server.use(function (req, res, next) { var users; // if (/* some condition determining whether the resource requires authentication */) { // return next(); // } users = { foo: { id: 1, password: 'bar' } }; // Ensure that user is not anonymous; and // That user exists; and // That user password matches the record in the database. if (req.username == 'anonymous' || !users[req.username] || req.authorization.basic.password !== users[req.username].password) { // Respond with { code: 'NotAuthorized', message: '' } next(new restify.NotAuthorizedError()); } else { next(); } next(); });
我想要的是转换大量的function代码在server.use(function (req, res, next) { ...
这样我可以像这样调用该函数server.use(verifyAuthorizedUser(req, res, next));
所以,我所做的就是创造这个function。
function verifyAuthorizedUser(req, res, next) { var users; // if (/* some condition determining whether the resource requires authentication */) { // return next(); // } users = { foo: { id: 1, password: 'bar' } }; // Ensure that user is not anonymous; and // That user exists; and // That user password matches the record in the database. if (req.username == 'anonymous' || !users[req.username] || req.authorization.basic.password !== users[req.username].password) { // Respond with { code: 'NotAuthorized', message: '' } next(new restify.NotAuthorizedError()); } else { next(); } next(); }//function verifyAuthorizedUser(req, res, next)
然后,我调用server.use(verifyAuthorizedUser(req, res, next));
。 不幸的是,我遇到了这个错误ReferenceError: req is not defined
。
你应该传递函数本身,而不是调用函数:
server.use(verifyAuthorizedUser);
编辑:更多细节:
-
verifyAuthorizedUser(req, res, next)
是对函数verifyAuthorizedUser
的调用 。 它的值将是该函数的返回值。 这将需要req
,res
和next
来定义,而不是。 -
你可以写:
server.use(function(req,res,next) { verifyAuthorizedUser(req, res, next); });
但是这只是添加额外的代码没有很好的理由。
-
server.use(verifyAuthorizedUser());
也是对这个函数的调用 ,而且你还有一个额外的问题,就是你没有传递任何参数给一个需要一些函数的函数,所以它显然会崩溃。
某些函数(如restify.queryParser
)可能会返回一个函数,在这种情况下,您将调用第一个函数(用()
)来获取函数作为callback。
尝试server.use(verifyAuthorizedUser)
。 这个callback函数将被传递所有的参数。
你不需要在callback中parsing参数。 做就是了
server.use(verifyAuthorizedUser)
欲了解更多信息,请点击这里
- 对象#<Readable>在使用Gulp + Browserify时没有方法“写入”
- 会logging要求个别良好的做法或混乱?
- 节点应用程序:Http到httpsredirect不适用于本地主机
- 如何使用请求js和jasminetesting一个使用file upload的nodejs POST Web服务?
- 如何在文件结构中组织nodejs导出,但没有创build具有相同结构的文件
- 确定节点stream是否在objectMode中
- 在Node.js Web应用程序中使用用户名和密码在Azure AD上进行身份validation
- 节点JSasynchronousPromise.All问题
- 节点handbrakejs运行代码,但不输出