首页 > 解决方案 > 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 页面,然后将我重定向回 l​​ocalhost,我的 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);”处有错误 给我“未定义的访问令牌!”

标签: javascriptnode.jsoauth-2.0xero-api

解决方案


所以这个错误是因为 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)

https://github.com/XeroAPI/xero-node


推荐阅读