You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Plaid Link集成Back4App遇报错:CORS及云函数无效问题求助

Let's tackle each of your errors one by one, since they're all connected to misconfigured frontend-backend communication and incorrect Back4App cloud code setup.

1. Fix "Invalid function: 'plaidAPI'" (Back4App Cloud Code Issue)

Back4App uses Parse Server's cloud function system—you can't use Express.js to define routes like /create_link_token directly in your cloud code. Instead, you need to wrap your Plaid logic into Parse Cloud Functions. Here's how to rewrite your cloud code:

const plaid = require('plaid');

// Initialize Plaid client
const client = new plaid.Client({
  clientID: 'YOUR_CLIENT_ID',
  secret: 'YOUR_SECRET',
  env: plaid.environments.sandbox
});

// Cloud function to create link token
Parse.Cloud.define('createLinkToken', async (request) => {
  // Get client_user_id (adjust this to fetch your actual user ID from Parse)
  const clientUserId = request.user.id; // Assumes user is authenticated; tweak if needed

  return new Promise((resolve, reject) => {
    client.createLinkToken({
      user: { client_user_id: clientUserId },
      client_name: 'My App',
      products: ['transactions'],
      country_codes: ['US'],
      language: 'en',
      webhook: 'https://sample.webhook.com'
    }, (error, linkTokenResponse) => {
      if (error) {
        reject(error);
      } else {
        resolve({ link_token: linkTokenResponse.link_token });
      }
    });
  });
});

// Cloud function to exchange public token for access token
Parse.Cloud.define('exchangePublicToken', async (request) => {
  const publicToken = request.params.public_token;

  return new Promise((resolve, reject) => {
    client.exchangePublicToken(publicToken, (error, response) => {
      if (error) {
        console.error('Public token exchange failed:', error);
        reject({ error: error.message });
      } else {
        // Store access_token and item_id in Parse (adjust to your data model)
        const user = request.user;
        user.set('plaidAccessToken', response.access_token);
        user.set('plaidItemId', response.item_id);
        return user.save().then(() => {
          resolve({ success: true });
        });
      }
    });
  });
});

Key changes here:

  • Replaced Express routes with Parse.Cloud.define to create proper Back4App cloud functions
  • Wrapped Plaid's callback-based methods in Promises to work with Parse's async cloud function system
  • Added logic to store Plaid tokens in the Parse User object (customize this to fit your app's data structure)

Your frontend is trying to fetch a local /create_link_token endpoint, but:

  • You're opening the HTML file directly (using file:// protocol), which doesn't support CORS or backend requests
  • Your backend logic is now in Back4App cloud functions, so you need to use Parse.Cloud.run() instead of fetch() to call them

Here's the corrected frontend JavaScript:

<!-- Keep your existing HTML structure, update the script section like this -->
<script type="text/javascript">
// Initialize Parse first (credentials.js should set these values)
Parse.initialize("YOUR_PARSE_APP_ID", "YOUR_PARSE_JS_KEY");
Parse.serverURL = "https://parseapi.back4app.com/";

(async function($) {
  const fetchLinkToken = async () => {
    // Call Back4App cloud function instead of fetching a local endpoint
    const response = await Parse.Cloud.run('createLinkToken');
    return response.link_token;
  };

  const configs = {
    token: await fetchLinkToken(),
    onLoad: function() {
      console.log('Plaid Link loaded');
    },
    onSuccess: async function(public_token, metadata) {
      // Call cloud function to exchange public token
      await Parse.Cloud.run('exchangePublicToken', { public_token: public_token });
      alert('Account linked successfully!');
    },
    onExit: async function(err, metadata) {
      if (err != null) {
        console.error('Plaid Link error:', err);
        if (err.error_code === 'INVALID_LINK_TOKEN') {
          handler.destroy();
          handler = Plaid.create({ ...configs, token: await fetchLinkToken() });
        }
      }
    },
    onEvent: function(eventName, metadata) {
      console.log('Plaid event:', eventName);
    }
  };

  let handler = Plaid.create(configs);

  $('#link-button').on('click', function(e) {
    handler.open();
  });
})(jQuery);
</script>

Key fixes here:

  • Added proper Parse initialization (critical for communicating with Back4App)
  • Replaced fetch('/create_link_token') with Parse.Cloud.run('createLinkToken')
  • Replaced the public token exchange fetch with Parse.Cloud.run('exchangePublicToken')
  • Removed the unused <script id="plaid">Parse.Cloud.run("plaidAPI")</script> line (we don't have a plaidAPI function anymore)

3. Additional Critical Checks

  • Serve your HTML over HTTP/HTTPS: Don't open it directly as a file. Use a local server (like http-server or VS Code's Live Server extension) to avoid file:// protocol issues.
  • Install Plaid in Back4App: Make sure you've added the plaid npm package to your Back4App project. Go to your Back4App dashboard > Cloud Code > npm > Install, then search for plaid.
  • Authenticate Users: The cloud functions above use request.user—make sure your frontend user is logged in with Parse before calling these functions, or adjust the client_user_id logic if you don't require authentication.

内容的提问来源于stack exchange,提问作者Pablo Picasso

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 23:07:31