Search code examples
reactjsnode.jsexpresshttpcors

Cors isn't working on express , even after setting it


i was given a web application to deploy , it was a fairly simple application with a react frontend and a node/express backend , everything seemed to be working fine , but the front end wasn't able to communicate with the api and it appears to be a cors issue .

This is a snippet of the frontend code that's making the request

import React, { useState } from "react";
import axios from "axios";
import { useNavigate } from "react-router-dom";

const LoginPage = () => {
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [error, setError] = useState("");
  const [loading, setLoading] = useState(false);
  const [success, setSuccess] = useState("");

  const navigate = useNavigate();

  const handleSubmit = async (e) => {
    e.preventDefault();

    if (!email || !password) {
      setError("Por favor, complete ambos campos.");
      return;
    }

    setLoading(true);
    setError("");
    setSuccess("");

    try {
      const response = await axios.post("http://backend:5000/user/login", {
        email: email,
        password: password,
      });

the backend is the name of the backend container (the containers are in the same bridged network and they are able to communicate)

This is the entrypoint of my backend

const express = require("express");
const mongoose = require("mongoose");
const dotenv = require("dotenv");
const cors=require("cors")
const connectDB = require("./config/db");
dotenv.config();

const app = express();

app.use(express.json());
app.use(cors({
        origin: '*',
}))
connectDB();

const contactRoutes = require("./routes/contactRoutes");
const userRoutes = require('./routes/UserRoutes');
app.use("/contact", contactRoutes);
app.use('/user', userRoutes);

const PORT = process.env.PORT || 5000;
app.listen(PORT, () => {
  console.log(`Server is running on http://localhost:${PORT}`);
});

and this what i found in the network tab this screenshot is taken from firefox and as you can see it's telling me CORS failed

and this is another screenshot from chrome google chrome screenshot 1

google chrome screenshot 2

ive tried different options in the cors and tried to use the exact domain in the origin , wether by using a domain name or an ip , i have also tried running them without docker and for the front end i tried to run it direcly and building it then running it on nginx , anyhelp would be appreciated since i've spent 10 hours straight trying to figure that out xD.


Solution

  • At the end it wasn't really CORS related , because if it was a CORS issue you would at least get a response . The problem was that my frontend was working over https and my backend was working over http , thus the browser was blocking the request due to a mixed content policy . The error was quite misleading especially in mozilla , (i guess chrome is a good browser to work on after all). So simply i altered the requests to be made to an endpoint on my domain and told nginx to forward them to my backend , this way the browser would have no reason to block the request from being sent.