Search code examples
reactjsnode.jsexpressservercors

Blocked by CORS policy despite domain name present in server side file


I've run into a very bizarre problem that even after hours of troubleshooting this issue persists.

Project Background

First of all, my front end is run on React+Vite (but I didn't really use anything Vite related), hosted on Vercel at let's say, https://mywebsite.ca

My backend is run on Express and Node, also hosted on Vercel at, https://backend.vercel.app

My MySQL Database is hosted on AWS RDS

The Issue

The issue is that everything for the Login or Sign up page works (Occasionally it says not server error but that's very rare). I didn't run into any CORS issue at this stage. However, the moment the user logs in (which directs me to https://mywebsite.ca/course-selection) I run into CORS issue.

I am pretty sure my CORS are all well defined as you can see in my index.js here:

import express from "express"
import cors from "cors"
import userRoutes from "./routes/users.js"
import authRoutes from "./routes/auth.js"
import courseChangeRoutes from "./routes/courseChange.js"
import cookieParser from "cookie-parser";


const app = express();
app.use(express.json());
app.use(cookieParser());

app.use(
    cors({
      origin: 'https://www.mywebsite.ca',
      methods: ['GET', 'POST', 'OPTIONS', 'PUT', 'DELETE'],
      credentials: true,
    })
);

app.use((req, res, next) => {
  res.header("Access-Control-Allow-Credentials", true);
  next();
});

app.use("/backend/users", userRoutes);
app.use("/backend/auth", authRoutes);
app.use("/backend/courseChange", courseChangeRoutes);

I even added in OPTIONS because I did some research and find out sometimes preflight requests are made using OPTIONS. However the issue persists and I still frequently get: Access to XMLHttpRequest at 'https://backend.vercel.app/backend/courseChange/' from origin 'https://www.mywebsite.ca' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Then followed with Failed to load resource: net::ERR_FAILED

Through monitoring the Networks Tab, there's many failed requests that looked like:

Request URL: https://backend.vercel.app/backend/courseChange/ Referrer Policy: strict-origin-when-cross-origin with the payload JSON that's in the correct format

OR Request URL: https://backend.vercel.app/backend/courseChange/ Request Method: OPTIONS Status Code: 500 Internal Server Error Referrer Policy: strict-origin-when-cross-origin

Other relevant files that might be helpful for troubleshooting

/operation/courseChange.js: (backend)


export const courseChange = async (req, res) => {
    const { userId, courses_ids, term } = req.body;

    if (!userId || !Array.isArray(courses_ids) || !term) {
        return res.status(400).send('Invalid input');
    }

    const maxCourses = 15; 

    try {
        // Clear existing courses for the specified term
        let clearQuery = 'UPDATE users SET ';
        for (let i = 1; i <= maxCourses; i++) {
            clearQuery += `${term}Course${i} = NULL, `;
        }
        clearQuery = clearQuery.slice(0, -2) + ' WHERE id = ?';
        console.log('Clear Query:', clearQuery, [userId]);
        await db.execute(clearQuery, [userId]);

        // Construct the update query for new courses
        let updateQuery = 'UPDATE users SET ';
        const updateValues = [];
        if (courses_ids.length > 0) {
            courses_ids.forEach((courseId, index) => {
                updateQuery += `${term}Course${index + 1} = ?, `;
                updateValues.push(courseId);
            });
            updateQuery = updateQuery.slice(0, -2);
            updateQuery += ' WHERE id = ?';
            updateValues.push(userId);


            console.log('Update Query:', updateQuery, updateValues);
            await db.execute(updateQuery, updateValues);
            res.status(200).send('Courses updated successfully');
            }

    } catch (error) {
        console.error('Error updating courses:', error);
        res.status(500).send('Error updating courses: ' + error.message);
    }
    
};

/pages/course-selection.jsx: (frontend)

import { useState, useEffect } from 'react';
import LeftMenu from '/src/components/leftMenu';
import Calendar from '/src/components/calendar';
import Nav from '/src/components/nav';
import Selection from '/src/components/selections';
import fallJSON from '/src/assets/fall_2024_0626.json';
import winterJSON from '/src/assets/winter_2025_0626.json';
import axios from 'axios'

axios.defaults.withCredentials = true;


export default function Courses() {

    const [fallCourses, setFallCourses] = useState([]);
    const [winterCourses, setWinterCourses] = useState([]);
    const [fallData, setFallData] = useState(fallJSON);
    const [winterData, setWinterData] = useState(winterJSON);
    const [err, setError] = useState(null);

    const updateFallCourses = async (courses_ids) => {
        // Prepare for Calendar Rendering
        const courses = courses_ids.flatMap(course => fallData[course].slice(2));
        setFallCourses(courses);
        // Send data to backend
        const user = JSON.parse(localStorage.getItem('user'));
        const userId = user ? user.id : null;
        const term = "fall"
        try {
            await axios.post('https://backend.vercel.app/backend/courseChange/', {
                userId,
                courses_ids,
                term,
            }, {
                headers: {
                    'Access-Control-Allow-Origin': '*',
                    'Content-Type': 'application/json',
                }
            });
            console.log('Courses updated successfully');
        } catch (err) {
            const errorMessage = err.response?.data?.message || "An unexpected error occurred";
            setError(errorMessage);
        }

    };

// There's also const updateWinterCourses right here that basically is the same code

Unpredictable Behavior

Finally, something unexpected, upon invoking the function updateFallCourses, one of the following could happen:

  1. The CORS and the ERR errors are printed into the console, nothing happens
  2. The CORS and ERR errors don't appear I get a message that "Courses updated successfully" and database is updated
  3. Just like 2, no errors, success message, but the database is NOT updated.

Somethings I've tried include: allowing connections for all OPTIONS request in index.js, but that didn't fix my issue. Also if it matters, everything works very smoothly when I run my backend on http://localhost:8800 and frontend on http://localhost:3000 without any CORS issue (obviously back then the origin defined in the CORS would be localhost:3000).

I am genuinely stuck and wish to launch the site in a day or two. This is the last step since without being able to update the user changes to database I'm missing the most important function. I would appreciate any advice at all! Since this is my first full stack project, if you have relevant tips for how to manage different ends or if some code could be written in a cleaner way I would greatly appreciate it as well! Thanks!!


Solution

  • Alright guys I'm not sure what I did but it now works.

    Here's what's in my index.js

    const app = express();
    
    app.use(express.json());
    app.use(cookieParser());
    
    app.use(cors({
      origin: ["https://www.mywebsite.ca", "http://localhost:3000"], // Allow requests from this origin
      methods: ['GET', 'POST', 'PUT', 'DELETE'], // Allow these HTTP methods
      allowedHeaders: ['Content-Type', 'Authorization'], // Allow these headers
      exposedHeaders: ['Authorization'], // Headers that clients are allowed to access
      credentials: true, // Allow sending cookies along with requests
      maxAge: 86400, // Cache preflight request for 1 day (in seconds)
    }));
    
    app.options('*', (req, res) => {
      res.sendStatus(200);
    })
    

    It seems like maxAge and the line to return 200 for all options request would help