Gary Dickerson
Gary Dickerson

Reputation: 361

Getting a CORS error when trying to onboard users to Stripe Connect with Node.js

I am trying to set up our platform to allow users to be able to connect from our platform using Stripe Connect.

I am following the stripe-examples/connect-onboarding-for-standard that is linked to the documentation. Here is the code that I am using.

app.get("/api/stripe/onboard-user/refresh", async (req, res) => {
  if (!req.session.accountID) {
    res.redirect("/");
    return;
  }

  try {
    const { accountID } = req.session;
    const origin = `${req.secure ? "https://" : "https://"}${req.headers.host}`;

    const accountLink = await stripe.accountLinks.create({
      type: "account_onboarding",
      account: account.id,
      refresh_url: `${origin}/api/stripe/onboard-user/refresh`,
      return_url: `${origin}/settings/invoicing`,
    });

    res.redirect(303, accountLink.url);
  } catch (err) {
    res.status(500).send({
      error: err.message,
    });
  }
});

Every thing works find down to the res.redirect(303, accountLink.url); At that point it throws an error.

Access to XMLHttpRequest at 'https://connect.stripe.com/setup/s/1JdWa4pVJGhR' (redirected from 'https://localhost:4200/api/stripe/onboard-user') from origin 'https://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

I can pull the url from the error message and put it in a browser and it go to the page fine and I can finish the process. I have tried changing headers but have not found a solution.

Upvotes: 0

Views: 2293

Answers (1)

koopajah
koopajah

Reputation: 25552

The error often happens because your client-side code is making a GET request to your server, expecting a JSON response in an AJAX/fetch call, but your server is redirecting directly. That fails since the browser doesn't know what to do in this situation.

Usually, what you need to do is change your client-side call to not do a fetch() or AJAX equivalent and instead do a full page submission to your endpoint that will then redirect. Alternatively, you need to return the URL in your Node.js code instead of the redirect and have your client extract the URL from the response and redirect.

Upvotes: 4

Related Questions