javascript - Xero-Node 未定义的回调参数
问题描述
我正在使用以下内容: https ://github.com/XeroAPI/xero-node
我正在使用 React 应用程序,与 Nodejs 后端交谈。React 应用程序调用节点文件 connect.js,如下所示:
// connect.js (node module)
const XeroClient = require('xero-node').XeroClient;
async function connect(req, res, next) {
try {
const xero = new XeroClient({
clientId: '9.............(hidden for SO)',
clientSecret: 'p...........(hidden for SO)',
redirectUris: [`http://localhost:3000/xeroCallback`],
scopes: 'openid profile email accounting.transactions offline_access'.split(" ")
});
let consentUrl = await xero.buildConsentUrl();
res.send(consentUrl);
} catch (err) {
console.log(err);
}
}
module.exports = connect;
这会将 URL 返回到我的 React 前端,这会触发重定向
这很好用,我进入 Xero Auth 页面,然后将我重定向回 localhost,我的 React 前端从后端调用 .callback.js,并从 Xero 发送过去的 URL:
{"http://localhost:3000/xeroCallback?code":"3......(hidden for SO)","scope":"openid profile email accounting.transactions","session_state":"E.........(hidden for SO)"}
这是我在 callback.js 中的代码
// callback.js (node module)
const { TokenSet } = require('openid-client');
const XeroClient = require('xero-node').XeroClient;
async function callback(req, res) {
const xero = new XeroClient({
clientId: '9.............(hidden for SO)',
clientSecret: 'p...........(hidden for SO)',
redirectUris: [`http://localhost:3000/xeroCallback`],
scopes: 'openid profile email accounting.transactions offline_access'.split(" ")
});
try {
await xero.initialize()
const TokenSet = await xero.apiCallback(req.body);
res.send(TokenSet);
} catch (err) {
console.log(err);
}
}
module.exports = callback;
“const TokenSet = await xero.apiCallback(req.body);”处有错误 给我“未定义的访问令牌!”
解决方案
所以这个错误是因为 Xero 客户端还没有被正确初始化。
https://github.com/XeroAPI/xero-node/blob/master/src/XeroClient.ts#L99
正如您在下面的代码(上面链接)中看到的,callbackParams 函数是 openIdClient (一个 oauth2.0 库)上的一个方法 - 为了完全设置他们的客户端,您需要调用xero.initialize()
或者xero.buildConsentUrl()
它看起来也应该是传回 req.url,虽然 req.body 可能仍然有效..
this.openIdClient.callbackParams(callbackUrl)
它以这种方式设置,以允许不需要/不想通过要求 openid-client 来访问帮助程序的人们使用更多不同的用例。
// This needs to be called to setup relevant openid-client on the XeroClient
await xero.initialize()
// buildConsentUrl calls `await xero.initialize()` so if you wont
// need to also call initialize() if you are sending user through auth
await xero.buildConsentUrl()
// You can also refresh the token without needing to initialize the openid-client
// helpful for background processes where you want to limit any dependencies (lambda, etc)
await xero.refreshWithRefreshToken(client_id, client_secret, tokenSet.refresh_token)
推荐阅读
- python - 如何改进我的 karatsuba Logic 以使我的代码正常工作?
- c# - 在查询窗口中运行但不是从代码中运行是什么问题?
- javascript - 全屏 Chart.js,同时保持图表质量
- php - 如何在mailchimp中使用名字和姓氏在列表电子邮件中添加成员?
- tensorflow - Tensorboard:为什么姓氏前缀两次?
- javascript - 如何使用jquery直接打印标签
- java - Spring Boot:如何在 Spring Context 启动时运行服务器并在执行测试期间在上下文关闭期间停止它?
- r - 闪亮的应用程序在控制台中提交代码时运行,但在选择运行应用程序按钮时不运行
- c# - 如何使用 ASP.NET MVC Rest API 调用和 jQuery Ajax 下载文件
- javascript - 如何使用d3旋转?