axios 从我的React应用程序连接到Xero Accounting API

f4t66c6m  于 2023-10-18  发布在  iOS
关注(0)|答案(1)|浏览(121)

我正在尝试从我的react应用程序本地连接到Xero Accounting API。我有一个this API调用设置,因此它向后端授权发送一个调用,然后我有一个回调API调用,它将返回一个access_token,我可以使用它来调用数据。
这是我用来调用Xero API的代码

import { useLocation } from "react-router-dom";
import useXero from "../../hooks/useXero";

const SigninToXero: React.FC = () => {
  const location = useLocation();
  const queryParams = new URLSearchParams(location.search);
  const authorizationCode = queryParams.get("code");

  const handleAuthorizeClick = () => {
    window.location.href = "http://localhost:4000/authorize";
  };

  return <button onClick={handleAuthorizeClick}>Authorize Xero</button>;
};

export default SigninToXero;
const express = require("express");
const xero = express.Router();
const schemas = require("../models/schemas");

const clientId = "xxx";
const clientSecret = "xxx";
const redirectUri = "http://localhost:4000/callback";

xero.get('/authorize', (_, res) => {
  // Redirect users to the Xero authorization endpoint
  const authorizeUrl = `https://login.xero.com/identity/connect/authorize?response_type=code&client_id=${clientId}&redirect_uri=${redirectUri}`;
  res.redirect(authorizeUrl);
});

xero.get("/callback", async (req, res) => {
  const authorizationCode = req.query.code;

  // Exchange authorization code for an access token
  const tokenResponse = await axios.post(
    "https://identity.xero.com/connect/token",
    null,
    {
      params: {
        client_id: clientId,
        client_secret: clientSecret,
        code: authorizationCode,
        grant_type: "authorization_code",
        redirect_uri: redirectUri,
      },
    }
  );

  const accessToken = tokenResponse.data.access_token;
  res.send("Access token obtained successfully", accessToken);
});

module.exports = xero;

下面是节点服务器的代码

const express = require("express");
const cors = require("cors");
const bodyParser = require("body-parser");
const router = require("./routes/router");
const xero = require("./routes/xero")
const mongoose = require("mongoose");
require("dotenv/config");

const app = express();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

const corsOptions = {
  origin: "*",
  credentials: true,
  optionSuccessStatus: 200,
};

app.use(cors(corsOptions));
app.use("/", router);
app.use("/", xero)

const dbOptions = { useNewUrlParser: true, useUnifiedTopology: true };
mongoose
  .connect(process.env.DB_URI, dbOptions)
  .then(() => console.log("DB connected!"))
  .catch(err => console.log(err))

const port = process.env.PORT || 4000;
const server = app.listen(port, () => {
  console.log(`Server is running on port ${port}`);
});

我期待从API的响应,说“访问令牌成功获得,(访问令牌)”

bfhwhh0e

bfhwhh0e1#

Xero的API目前不支持单页应用程序。您将能够连接到Xero组织,但呼叫将无法工作。
https://developer.xero.com/documentation/guides/oauth2/overview/文档提到目前不支持SPA。

相关问题