badiboytr
badiboytr

Reputation: 11

CORS issue between React frontend and Express backend deployed on Vercel

I'm developing a full-stack application where the frontend is built with React and the backend with Express.js. Both the frontend and backend are deployed separately on Vercel.

I'm trying to send a POST request from the frontend to the backend to handle payments, but I keep encountering a CORS error:

Access to fetch at 'https://askida-backend.vercel.app/payment/create' from origin 'https://www.asunatech.com' 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. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
  1. Is there something wrong with my CORS configuration in Express or the way I’ve set up environment variables?
  2. Could Vercel’s deployment have specific CORS settings that I need to account for?
  3. How can I properly resolve this CORS issue so that requests from https://www.asunatech.com to my backend are allowed?

Any help or suggestions would be greatly appreciated!

In my backend, I’ve set up CORS like this:

const cors = require('cors');
const allowedOrigins = [
  'https://www.asunatech.com',
  'http://localhost:3000' // For local development
];

app.use(cors({
  origin: function (origin, callback) {
    if (!origin || allowedOrigins.includes(origin)) {
      callback(null, true);
    } else {
      callback(new Error('Not allowed by CORS'));
    }
  },
  methods: ['GET', 'POST', 'OPTIONS'], // Allow necessary methods
  credentials: true,
  allowedHeaders: ['Content-Type', 'Authorization'], // Custom headers
}));

// Ensure preflight requests are handled
app.options('*', cors());

The frontend makes a POST request using fetch:

const apiUrl = process.env.REACT_APP_API_URL_PRODUCTION;

const handleSubmit = async () => {
  const payload = {
    email: formData.email,
    phone_number: formData.phone_number,
    price: calculateTotal(),
  };

  try {
    const response = await fetch(`${apiUrl}/payment/create`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(payload),
    });

    if (!response.ok) {
      throw new Error('Payment failed');
    }
  } catch (error) {
    console.error('Error during payment submission:', error);
  }
};

Allowed Headers in CORS: I have specified the necessary headers (Content-Type, Authorization) in my CORS configuration. Despite the CORS setup in my Express backend, I'm still facing this error:

Access to fetch at 'https://askida-backend.vercel.app/payment/create' from origin 'https://www.asunatech.com' 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. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

Upvotes: 1

Views: 131

Answers (1)

Hamed Jimoh
Hamed Jimoh

Reputation: 801

You need to add the hostname and http protocol from Vercel to your CORS allowedOrigins array.

const allowedOrigins = [
  'https://www.asunatech.com',
  'http://localhost:3000', // For local development
  'https://askida-backend.vercel.app'
];

Upvotes: 0

Related Questions