Avoiding Access-Control-Allow-Origin cors issue when integrating with Stripe

Currently, I am working on setting up a payment system using Stripe. Below is the post request code I am using with Express:

try {
    const session = await stripe.checkout.sessions.create({
      line_items: [
        {
          price: `${priceId}`, // Make sure to replace this with the Price ID
          quantity: 1,
        },
      ],
      mode: 'payment',
      success_url: `${process.env.SUCCESSURL}?success=true`, // Redirect if payment successful
    });

    return res.redirect(303, session.url);
  } catch (error) {
    console.log("Error with payment checkout session: ", error);
  }

This is how my frontend axios request looks like:

const checkout = () => {
    axios({
      method: "post",
      url: "http://localhost:4000/api/payment/create-checkout-session",
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json',
        "Authorization": `Bearer ${token}`,
      }
    })
    .then((response) => {
      const { data } = response;
      
        window.location = data.url;
    })
    .catch((error) => {
      console.log(error);
    });
  }

I'm encountering an issue related to CORS and the link to Stripe:

Access to XMLHttpRequest at 'https://checkout.stripe.com/c/pay/cs_test_ (redirected from 'http://localhost:4000/api/payment/create-checkout-session') from origin 'http://localhost:3000' 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.

Here's my CORS configuration:

app.use(
  cors({
    origin: 'http://localhost:3000', // Replace this with your frontend's origin
  })
);

I'm struggling with the error message saying 'No 'Access-Control-Allow-Origin' header is present on the requested resource.' I don't fully grasp what action needs to be taken to address this issue.

Answer №1

There are a couple of solutions to address this issue, and you have the option to select either of the following methods:

  • [Frontend]: Opt for utilizing HTML form POST request instead of XMLHttpRequest to establish a checkout session and carry out a redirect. For sample code, please check this resource
  • [Backend]: Replace 303 with a 200 response that includes the session URL. Handle the output on your frontend and utilize JavaScript window.open(sessionUrl) to launch the Billing Portal.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Node.js Express Logging in AWS Fargate: A comprehensive guide

In the process of creating a Nodejs/Express app to run on AWS Fargate, I am looking for guidance on logging. Specifically, I want to ensure that my app logs are easily accessible in AWS Cloudwatch. Can anyone recommend the most effective method for loggi ...

Why does Material-UI's "withStyles()" not function properly with a specified constructor in Typescript?

Update: Please note that there was an issue with the constructor generated by IntelliJ IDEA, but it has been fixed. You can find more details here: I'm exploring the use of Material-UI in my application, and I've encountered some challenges wit ...

Exciting Update: Next.js V13 revalidate not triggering post router.push

Currently using Next.js version 13 for app routing, I've encountered an issue with the revalidate feature not triggering after a router.push call. Within my project, users have the ability to create blog posts on the /blog/create page. Once a post is ...

PNPM and Storybook error: No configuration files were detected in the specified config directory

I am facing challenges setting up a Storybook documentation project in my PNPM monorepo. I have attempted to add it to an existing app and create a new project, but encountered the same error message both times: Error: No configuration files have been fou ...

Incorporating images with JavaScript in Jade templates

Currently I have a layout.jade code that I am looking to modify the javascript for. My goal is to load an image onto the page every time it is reloaded using jade. Here is the existing code: html head title= title script(src='/libs/jquery/j ...

What are the differences in performance when comparing Express JS and pure Node.js?

I'm curious - has anyone come across any benchmark data comparing the use of the Express JS framework with pure Node.js? Do you think it's necessary to consider this comparison, or is using Express or a similar framework essential when developi ...

I assigned a key prop to the child component, but I am still encountering the error message: "Each item in a list must have a distinct 'key' prop"

I am currently utilizing MongoDB and Express for the backend of my project. Here is part of my component: return ( <> <Addnote /> <div className="row my-3"> {notes.map((note) => { ...

Encountered an issue while attempting to connect MongoDB to Node.js

``const timeoutError = new error_1.MongoServerSelectionError(Server selection timed out after ${serverSelectionTimeoutMS} ms, this.description); .MongoServerSelectionError: connect ECONNREFUSED ::1:27017 const {MongoClient}=require('mongodb'); c ...

Establishing specific categories for a universal element

I have been working on creating an input component that functions as a custom select for enums in my application. I have tried defining them for different types using concise one-liners but have run into various typing issues. Here is what I have so far: ...

Oops! Looks like there's an issue with reading the property 'value' of undefined in React-typeahead

Having some issues with setting the state for user selection in a dropdown menu using the react-bootstrap-typeahead component. Any guidance or resources on this topic would be highly appreciated. Details can be found here. The function handleAddTask is su ...

Invalid parameter or query values detected in the next.js server-side rendering context

Take a look at my directory structure in next.js for handling dynamic routes. In my product page Server Side (SSR), I utilize params in this manner: While most of the time I am able to retrieve correct values, there are instances when productId returns t ...

Managing data retrieval within React SSR frameworks for components outside of routes

As I delve into the world of React SSR frameworks like Next.js, Remix, and more, a burning question arises regarding data retrieval in components not linked to specific routes. Typically, these frameworks handle data loading at the route level, but what ab ...

After integrating redux and setting up private/public routing, the component will not be re-rendered by the `<Link>` element

An update has been made: A demo has been uploaded on CodePen. You can find it here I am currently using a Drawer from the material-ui CSS library, specifically for an admin control panel. The Drawer consists of the AppRouter component. When I navigate thr ...

Display problem with concealed container

I am facing an issue with the values in my component appearing correctly, but when I display a hidden div, they seem to be incorrect. I suspect it might be a rendering problem, but I have been unable to find a solution. The component (code provided below) ...

Creating a precise regular expression for route length in Express JS

Currently, I am facing an issue while setting a route in my application. I want the URL parameter to be exactly 2 characters long, but unfortunately, the following code snippet is not producing the desired result: app.all('/:lng{2}?',function (r ...

A step-by-step guide to showing images in React using a JSON URL array

I successfully transformed a JSON endpoint into a JavaScript array and have iterated through it to extract the required key values. While most of them are text values, one of them is an image that only displays the URL link. I attempted to iterate through ...

Having trouble retrieving the user-object within tRPC createContext using express

I'm encountering an issue with my tRPC configuration where it is unable to access the express session on the request object. Currently, I am implementing passport.js with Google and Facebook providers. Whenever I make a request to a regular HTTP rout ...

What are some strategies for stopping a form from redirecting me while utilizing ReactJS and ExpressJS?

Recently, I created a form that redirects to the route /repair upon submission with an action of /repair. However, I would prefer to keep it as a Single Page Application (SPA) where after submitting the form, the fields are cleared, and a simple message l ...

Logging with Nextjs server on production mode

I have encountered an issue with my Next.js 14 project that uses server-side rendering. I noticed that when I add console.log and Winston logger to my server components, the logs are displayed when I run npm run build. However, when I try to run npm run st ...

Distinguishing Between Two Comparable ExpressJS RoutesWhen working with ExpressJS,

I am facing an issue with two routes in my API: /api/persons/:personId and /api/persons/contact. The problem arises when I hit the route api/persons/contactS (with an extra 'S' character) as it mistakenly triggers the API code for api/persons/:pe ...