gpt4 book ai didi

javascript - 在 API Client 中公开 Expressjs 中间件

转载 作者:太空宇宙 更新时间:2023-11-04 02:22:25 24 4
gpt4 key购买 nike

我正在开发一个采用这种简单形式的 Nodejs API 客户端:

//client.js
function Client (appId, token) {

if (!(this instanceof Client)) {
return new Client(appId, token);
}

this._appId = appId;
this._token = token;
...
}

Client.prototype.save = function (data,callback) {
return this_request(...);
}

Client.prototype._request = function (method, url, data, callback) {
//do stuff
}

module.exports = Client

我现在希望在 Expressjs 路由中提供一个 auth 函数作为中间件,但我不确定如何将该函数集成到 client.js 中。

var myModule = require('myModule');
var thingy = myModule("12345", 'abcde');

router.get('/protectedRoute', thingy.auth, function(req, res, next){

}

例如,函数是否应该被定义为原型(prototype)的一部分,如下所示:

Client.prototype.auth = function(req,res,next) {
//do stuff
}

非常感谢任何指示和建议。

最佳答案

因此,中间件的实现方式是,您必须为其传递一个函数,然后使用 req resnext 调用它。当您采用 OOP 方法并将 auth 设为对象的原型(prototype)方法时,当该函数被 express 调用时,它将具有不同的 this 作用域,因此可能会引发错误。您需要使用 bind 创建一个将特定范围绑定(bind)到该函数的函数,然后将其传递给express。

router.get('/protectedRoute', thingy.auth.bind(thingy), function(req, res, next){

}

或者:

var authMiddleware = function(req, res, next) {
thingy.auth(req, res, next);
}

router.get('/protectedRoute', authMiddleware, function(req, res, next){

}

关于javascript - 在 API Client 中公开 Expressjs 中间件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32540599/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com