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:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>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);
</code>
<code>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); </code>
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

Other relevant files that might be helpful for troubleshooting

/operation/courseChange.js: (backend)

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>
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);
}
};
</code>
<code> 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); } }; </code>

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)

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>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
</code>
<code>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 </code>
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

context/authContext.jsx (that handles login logout, fully works)

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>import axios from "axios";
import { createContext, useEffect, useState } from "react";
export const AuthContext = createContext();
export const AuthContextProvider = ({ children }) => {
const [currentUser, setCurrentUser] = useState(
JSON.parse(localStorage.getItem("user")) || null
);
const login = async (inputs) => {
const res = await axios.post("https://backend.vercel.app/backend/auth/login", inputs, {
withCredentials: true,
});
setCurrentUser(res.data)
};
const logout = async () => {
await axios.post("https://backend.vercel.app/backend/auth/logout", {}, {
withCredentials: true
});
setCurrentUser(null);
};
useEffect(() => {
localStorage.setItem("user", JSON.stringify(currentUser));
}, [currentUser]);
return (
<AuthContext.Provider value={{ currentUser, login, logout }}>
{children}
</AuthContext.Provider>
);
};
</code>
<code>import axios from "axios"; import { createContext, useEffect, useState } from "react"; export const AuthContext = createContext(); export const AuthContextProvider = ({ children }) => { const [currentUser, setCurrentUser] = useState( JSON.parse(localStorage.getItem("user")) || null ); const login = async (inputs) => { const res = await axios.post("https://backend.vercel.app/backend/auth/login", inputs, { withCredentials: true, }); setCurrentUser(res.data) }; const logout = async () => { await axios.post("https://backend.vercel.app/backend/auth/logout", {}, { withCredentials: true }); setCurrentUser(null); }; useEffect(() => { localStorage.setItem("user", JSON.stringify(currentUser)); }, [currentUser]); return ( <AuthContext.Provider value={{ currentUser, login, logout }}> {children} </AuthContext.Provider> ); }; </code>
import axios from "axios";
import { createContext, useEffect, useState } from "react";

export const AuthContext = createContext();

export const AuthContextProvider = ({ children }) => {
  const [currentUser, setCurrentUser] = useState(
    JSON.parse(localStorage.getItem("user")) || null
  );

  const login = async (inputs) => {
    const res = await axios.post("https://backend.vercel.app/backend/auth/login", inputs, {
      withCredentials: true,
    });

    setCurrentUser(res.data)
  };

  const logout = async () => {
    await axios.post("https://backend.vercel.app/backend/auth/logout", {}, {
      withCredentials: true
    });
    setCurrentUser(null);
  };

  useEffect(() => {
    localStorage.setItem("user", JSON.stringify(currentUser));
  }, [currentUser]);

  return (
    <AuthContext.Provider value={{ currentUser, login, logout }}>
      {children}
    </AuthContext.Provider>
  );
};

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!!

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật