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

131
Vistas
Redirecting to a React Component - Express

I have a Login component on the front in which I make a POST to a rout on the server:

const handleSubmit = async (e) => {
    e.preventDefault();
    try {
      fetch("http://localhost:3000/login", {
        method: "POST",
        mode: "cors",
        headers: {
          "Content-Type": "application/json",
          "Access-Control-Allow-Origin": "*",
        },
        body: JSON.stringify({
          email,
          password,
        }),
      });
    } catch (error) {
      console.log(error.message);
    }
  };

On the server side, I validate the information sended from the front:

app.post("/login", async (req, res) => {
  const user = await Users.findOne({
    where: { email: req.body.email, password: req.body.password },
  });
  if (user) {
    console.log(user);
    console.log("usuario logeado");

    res.status(200).send("LOGGED");
    
  } else {
    console.log("Usuario no Registrado");
  }
});

I want to redirect to a component Home on the front once I validate the user and idk how to do it.

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

You need to read the response from the server and figure out what you want to do with it. I'd recommend not sending just a string from the server, so this solution will restructure a bit to hopefully help you understand and expand for your own needs.

// From your server - we're sending some json that we can
// read in the front end code. Maybe you also want to send
// the user object or other data, and json is great for that.
app.post("/login", async (req, res) => {
  const user = await Users.findOne({
    where: { email: req.body.email, password: req.body.password },
  });
  if (user) {
    console.log(user);
    console.log("usuario logeado");

    res.status(200).send({
      isLoggedIn: true,
    });
    
  } else {
    console.log("Usuario no Registrado");
    res.status(200).send({
      isLoggedIn: false,
    });
  }
});
const handleSubmit = async (e) => {
    e.preventDefault();
    try {
      const response = await fetch("http://localhost:3000/login", {
        method: "POST",
        mode: "cors",
        headers: {
          "Content-Type": "application/json",
          "Access-Control-Allow-Origin": "*",
        },
        body: JSON.stringify({
          email,
          password,
        }),
      });
      // Get the server response as json
      const data = await response.json()
      if(data.isLoggedIn) {
        // Redirect to the account
        window.location.href = "/account"
      } else {
        // Show some error message
        window.alert("Invalid login")
      }
    } catch (error) {
      console.log(error.message);
    }
  };
over 4 years ago · Santiago Trujillo 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