我在nodejs上做我的第一个测试应用程序。这很简单。从api获取数据并将其显示在浏览器上。以下是我遵循的步骤。
使用pug(Was Jade)teplate引擎将其显示在浏览器中。
var express = require('express'); var tools = require('./ tools'); var app = express(); var request = require('request'); app.set('view engine','pug');
//获取令牌密钥 tools.generateToken(功能(响应){ token = response; });
//索引页面路由 app.get('/',function(req,res){ //res.send('Hello World'+令牌); var request = require('request'); request('URL?access_token ='+ token +'& n = 10& pgno = 2',function(error,response,body){ if(!error&& response.statusCode == 200){
res.render('index', { layout : 'layout', json: JSON.parse(body) });
}
})
});
var server = app.listen(3000,function(){
var host = server.address()。address var port = server.address()。port
console.log(“在http://%s:%s监听的示例应用”,主机,端口)
})
一切似乎都很好。但是一旦令牌过期,我就无法检索任何结果(很明显)。但我不知道何时获得新令牌。什么时候应该回忆一下令牌生成函数?
还有没有办法在没有浏览器刷新的情况下跟踪api数据更改?请帮忙。谢谢
答案 0 :(得分:0)
您可以使用reqclient,它是request
之上的小型客户端库,允许您自动处理OAuth2令牌刷新过程,因此如果OAuth2服务器为您提供过期时间响应,reqclient
将知道何时必须在没有任何干预的情况下请求新的。
还有其他很好的功能,如 cURL 日志记录,以了解请求是如何进行的,承诺对象来处理响应等。它也可以与{{一起安装1}}。
这是一个如何创建npm
对象来处理针对API的请求的示例,还告诉模块谁是OAuth2服务器,以及获取令牌的凭据是什么:
RequestClient
这两个请求都会返回Promise个对象,因此您必须处理var client = new RequestClient({
baseUrl: "https://api.example.com/myapi"
,debugRequest:true, debugResponse:true // (optional) this activate curl logging
,oauth2: {
baseUrl: 'https://auth.example.com/oauth2'
,auth: {
user: 'client123' // The username, also called "client_id"
,pass: 'thePass123' // The password, also called "client_secret"
}
}
});
client.get("home-reports") // First will try to login with OAuth2, then /home-reports
.then(client.get("messages")); // Will reuse the previous token obtained if it's not expired yet, otherwise it will request a new one first
和then
如何处理它们。无论如何,因为使用catch
(可选)激活了日志记录,所有请求和响应都将在控制台中记录,如下所示:
debugRequest:true, debugResponse:true