0

I get the following error when using Stripe in React. I'm assuming my server is set-up right. So how do I resolve an Access-Contorl-Allow-Origin error?

> Access to fetch at 'http://localhost:9000/charge' from origin
> 'http://localhost:3000' has been blocked by CORS policy: No
> 'Access-Control-Allow-Origin' header is present on the requested
> resource. If an opaque response serves your needs, set the request's
> mode to 'no-cors' to fetch the resource with CORS disabled.

  async submit(ev) {
  let {token} = await this.props.stripe.createToken({name: "Name"});
  let response = await fetch("http://localhost:9000/charge", {
     method: "POST",
     headers: {"Content-Type": "text/plain"},
     mode: "no-cors",
     body: token.id
   });
 if (response.ok) this.setState({complete: true});
 }

This is the tutorial I'm following... https://stripe.com/docs/recipes/elements-react

As a follow up, the error was resolved using one of their test credit cards... https://stripe.com/docs/testing

Rob B.
  • 130
  • 1
  • 7
  • 24
  • Are you sure you have CORS set up properly? The error says it didn't get a `Access-Control-Allow-Origin` header in response. You can try and set it to `*` in the beginning when you are just testing. – Tholle Nov 01 '18 at 23:13
  • If your applications is hosted in IIS Server 8+, you may remove OPTIONSVerbHandler from web.config file. – Carlos Huchim Nov 01 '18 at 23:17
  • I tried setting up the headers like this... headers: {"Content-Type": "text/plain", "Access-Control-Allow-Origin": "*"}, – Rob B. Nov 01 '18 at 23:19

1 Answers1

0

The error speaks for itself. Your express server (I assume you follow the tutorial and your backend is written in express) has not been configured to handle CORS properly.

The idea behind CORS is that if the browser request resource from a different domain, it needs to be given the permission to do so by this resource itself.

For express, you can either use the cors middleware to handle cors properly, or do it yourself as so in the link here: https://enable-cors.org/server_expressjs.html

Thai Duong Tran
  • 2,453
  • 12
  • 15
  • I tried adding the below code to the server.js file however it didn't work. I'm going to try cors middleware. app.use(function(req, res, next) { res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); next(); }); – Rob B. Nov 01 '18 at 23:30
  • @Thai , for those of us less familiar with CORS, could you explain how to configure `cors` properly. Suggesting that we do so without showing *how* to do so isn't super helpful. – Rylan Schaeffer Jun 17 '22 at 16:59