Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

211
Vistas
How do I send a variable from Express.js backend to React.js frontend?

I am trying to send my variable 'backEndResponse' with its value from my Express.js backend to my React.js Frontend. I am not quite sure how to send a variable from the backend to the frontend. I have searched around and can't find any good resources. I would appreciate any help.

Express.js Backend

function getcookie(req) {
    var authCookie = req.headers.cookie;
    if (authCookie = req.headers.cookie) {
        try {
            return authCookie
                .split('; ')
                .find(row => row.startsWith('Auth='))
                .split('=')[1];
        } finally {
            if (authCookie = result) {
                backEndResponse = true
                console.log(backEndResponse);
                console.log(result);
            } else {
                backEndResponse = false
                console.log(backEndResponse);
                console.log(result);
            }

        }
    } else {

    }
}

app.get('/auth', (req, res) => {
    getcookie(req)

    if (backEndResponse) {
        res.json(backEndResponse); // OR json({ message: "Authorised" })
      } else {
        res.json(backEndResponse); // OR json({ message: "Unauthorised" })
    }
});

Frontend React.js

    const useAuth = () => {
    const [data, setData] = useState();

      useEffect(() => {
          const fetchAuthData = () => {
            const result = axios('http://localhost:5000/auth');

            console.log(result)
            setData(result.data);
            
          };

          fetchAuthData()
      }, []);

      
    // Logic to check if backEndResponse is true or false
    if (data) {
        const authorized = {loggedIn: true}
        return authorized && authorized.loggedIn;
    } else {
        const authorized = {loggedIn: false}
        return authorized && authorized.loggedIn;
    }
  }


const ProtectedRoutes = () => {
    const isAuth = useAuth();
    return isAuth ? <Outlet/> : <Navigate to="/login" />;
}
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

You won't be able to send a variable directly, rather you will send a payload in a certain shape that best represents the data suited to the applications needs. To send a response payload in an express route use something like the following:

app.get('/auth', (req, res) => {
  // do some logic for `backEndResponse`...
  res.json(backEndResponse);
});

If you were intending to provide more information in the response such as HTTP headers differing based on the of backEndResponse then you might consider:

app.get('/auth', (req, res) => {
  // do some logic for `backEndResponse`...

  // send HTTP Ok if true, otherwise Bad Request
  // consider handling 400 and/or 500 errors too
  if (backEndResponse) {
    res.status(200).json(true); // OR json({ message: "Authorised" })
  } else {
    res.status(401).json(false); // OR json({ message: "Unauthorised" })
  }
});

A component fetching the above endpoint would be similar to:

const MyComponent = () => {
  const [data, setData] = useState();

  useEffect(() => {
    const fetchAuthData = async () => {
      const result = await axios('http://localhost:5000/auth');

      setData(result.data); // true/false OR { message: "Authorised" }
    };

    fetchAuthData();
  }, []);

  // display payload
  return (<div>{JSON.stringify(data)}</div>)
}

There is an opportunity to refactor the above into a custom hook should you find the need to reuse the functionality across multiple components.

about 4 years ago · Juan Pablo Isaza Denunciar

0

axios request is async function, so you should do like that,

const useAuth = async () => {
  try {
    const res = await axios.get('http://localhost:5000/auth', {
      withCredentials: true
    })
    return true
  } catch (e) {
    return false
  }
};
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda