Pau*_*ica 7 logic request node.js superagent
SuperAgent存储库中的此问题提到了.use在每个请求上添加逻辑的方法.例如,Authorization在令牌可用时为JWT 添加标头:
superagent.use( bearer );
function bearer ( request ) {
var token = sessionStorage.get( 'token' );
if ( token ) request.set( 'Authorization', 'Bearer ' + token );
}
Run Code Online (Sandbox Code Playgroud)
虽然最后一条评论告诉我这个功能再次起作用,但我无法让它发挥作用.
以下测试代码:
var request = require( 'superagent' );
request.use( bearer );
function bearer ( request )
{
// "config" is a global var where token and other stuff resides
if ( config.token ) request.set( 'Authorization', 'Bearer ' + config.token );
}
Run Code Online (Sandbox Code Playgroud)
返回此错误:
request.use( bearer );
^
TypeError: undefined is not a function
Run Code Online (Sandbox Code Playgroud)
您链接到的问题没有链接到任何提交,因此我们所能做的就是推测该功能是否已实现然后被删除,或者从未实现过.
如果您通读src,您将看到use只在Request构造函数的原型上定义,这意味着它只能在您开始构建请求后使用,如自述文件中所示.
换句话说,问题似乎是谈论一个已被删除或从未存在的功能.您应该使用自述文件中提到的语法.
var request = require('superagent');
request
.get('/some-url')
.use(bearer) // affects **only** this request
.end(function(err, res){
// Do something
});
function bearer ( request ){
// "config" is a global var where token and other stuff resides
if ( config.token ) {
request.set( 'Authorization', 'Bearer ' + config.token );
}
}
Run Code Online (Sandbox Code Playgroud)
您当然可以创建自己的包装器,这样您就不必为每个请求执行此操作.
var superagent = require('superagent');
function request(method, url) {
// callback
if ('function' == typeof url) {
return new superagent.Request('GET', method).end(url).use(bearer);
}
// url first
if (1 == arguments.length) {
return new superagent.Request('GET', method).use(bearer);
}
return new superagent.Request(method, url).use(bearer);
}
// re-implement the .get and .post helpers if you feel they're important..
function bearer ( request ){
// "config" is a global var where token and other stuff resides
if ( config.token ) {
request.set( 'Authorization', 'Bearer ' + config.token );
}
}
request('GET', '/some-url')
.end(function(err, res){
// Do something
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2779 次 |
| 最近记录: |