1

I'm working on a simple react e-commerce application using firebase cloud functions and express.js as backend. On trying to get the client secret, I got CORs error as depicted below:

    Access to XMLHttpRequest at 'http://localhost:5001/challenge-3e08a/us-central1/api/payments/create?23900' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Payment.js:31 Customer error logged >>>  Error: Network Error
    at createError (createError.js:16)
    at XMLHttpRequest.handleError (xhr.js:84)

I set up the cloud functions like so: index.js for the cloud functions

    const functions = require("firebase-functions");
const express = require("express");
const cors = require("cors"); //({ origin: true });
const stripe = require("stripe")(
  "sk_test_51HlmzWCtn9NABLoH_________0Xp9jXQ0g"
);

// - API

// - App Config
const app = express();

// - Middlewares
app.use(cors({
  origin : true
}));

app.use(express.json());

// - API routes
app.get("/", (request, response) => response.status(200).send("Hello World"));

app.post(
  "/payments/create",
  async (request, response) => {
    const total = request.query.total;

    console.log("Payment request received BOOM!!! for this amount --- ", total);

    const paymentIntent = await stripe.paymentIntent.create({
      amount: total, // sub-units of the currency
      currency: "usd",
    });

    // OK
    response.status(201).send({
      clientSecret: paymentIntent.client_secret,
    });

    response.json({ msg: "This is CORS-enabled for an allowed domain." });
  }
);

app.listen(5001, function () {
  console.log("CORS-enabled web server listening on port 5001");
});

// - Listen command
exports.api = functions.https.onRequest(app);

Below is a portion of payment component which makes a get request get the client secret from stripe after authentication. The client secret is to be used to authorize the payment on the ecommerce app. Please note: all the necessary import(s) were made so they're not included here so as not to make the question too long.

    import { getBasketTotal } from "./reducer";
    import axios from "./axios";

    function Payment() {
    const [{ basket, user }, dispatch] = useStateValue();
    const history = useHistory();

    const stripe = useStripe();
    const elements = useElements();

    const [succeeded, setSucceeded] = useState(false);
    const [processing, setProcessing] = useState("");
    const [error, setError] = useState(null);
    const [disabled, setDisabled] = useState(true);
    const [clientSecret, setClientSecret] = useState("");

    useEffect(() => {
        // generate the secpail stripe secret which allows us to charge a customer
        getClientSecret();
    }, [basket]);

    const getClientSecret = async () => {
        const response = await axios({
        method: "post",
        // currency total in sub-units
        url: `/payments/create?total=${getBasketTotal(basket) * 100}`,
        })
        .then((response) => console.log(response.data.clientSecret))
        .catch((error) => console.log("Customer error logged >>> ", error));

        setClientSecret(response.data.clientSecret);

        console.log("THE CLIENT SECRET IS >>> ", clientSecret);
    };

Would appreciate every help I can get as this is my first react project.

Guzzyman
  • 561
  • 6
  • 16
  • 37
  • In your client post request, you aren't sending any data in the body. Shouldn't a POST request put the data in the body? It appears that perhaps you're sending data in the query string. Probably not the source of your problem, but it looks like an odd way to use a POST request. – jfriend00 Nov 12 '20 at 00:52

1 Answers1

0

It's pretty much just this: https://stackoverflow.com/a/18643011/379538

Your frontend and backend are running on different ports but you haven't specifically allowed for that in your CORS settings.

If you're using create-react-app, you should consider proxying it instead though: https://create-react-app.dev/docs/proxying-api-requests-in-development/

floatingLomas
  • 8,553
  • 2
  • 21
  • 27