Home > database >  How I do redirect using Express. EJS with external javascript?
How I do redirect using Express. EJS with external javascript?

Time:09-27

I have a login form which is collect user email and password. Then I use JavaScript fetch to post data to express. then I use express validator check the inputs are correct. Then I send response res.status(200).redirect("/auth"); like this, but JavaScript is prevent the login page to redirect because in my external JavaScript I use e.preventDefault() function. But I want to redirect to next page. When I remove e.preventDefault() it stops the validation so I cant remove that. What should I do?

I'm using Node, Express Js, JSON file for storing Data, EJS Template with external JavaScript file. Aslo serving static JavaScript file too which is located in public/js/script.js file. Also using express-validator in middleware folder to validate the fields

Here is the express code:

export const loginsHandle = async (req, res) => {
  const {
    email,
    password,
  } = req.body;

  const errors = validationResult(req);
  if (!errors.isEmpty()) {
    return res.status(422).json({
      errors: errors.array(),
    });
  } else {
    try {
      var accountPP = new PP({
        email: email,
        password: password,
      });
      let addingData = JSON.parse(fs.readFileSync(accountDataFile, "utf-8"));
      addingData.push(accountPP);
      await fs.writeFileSync(accountDataFile, JSON.stringify(addingData));
      res.status(200).redirect("/auth");
    } catch (error) {
      console.log(error);
      res.status(200).send(error);
    }
  }
};

Here is external JavaScript :

const form = document.querySelector("form");
const emailInput = document.getElementById("email");
const passwordInput = document.getElementById("password");
const btn = document.getElementById("submit");
const forGot = document.getElementById("forgot");
const singBtn = document.getElementById("sign");
const footer = document.getElementById("menuFoot");


forGot.addEventListener("click", (e) => {
  e.preventDefault();
});
singBtn.addEventListener("click", (e) => {
  e.preventDefault();
});
footer.addEventListener("click", (e) => {
  e.preventDefault();
});


form.onsubmit = sendLogin;

function sendLogin(e) {
  e.preventDefault();
  let formData = new FormData(form);
  let Params = {
    headers: {
      "Content-Type": "application/json",
      accept: "application/json",
    },
    body: JSON.stringify({
      email: formData.get("email"),
      password: formData.get("password"),
    }),
    method: "POST",
  };
  fetch("http://localhost:5001/login", Params)
    .then((res) => {
      return res.json();
    })
    .then((data) => {
      if (data.errors) {
        data.errors.forEach((err) => {
          if (data.errors[0].param == "email") {
            emailInput.style.borderColor = "red";
          } else if (data.errors[0].param == "password") {
            passwordInput.style.borderColor = "red";
          } else {
            emailInput.style.borderColor = "";
            passwordInput.style.borderColor = "";
          }
        });
      }

      return data;
    })
    .catch((error) => console.log(error, "error"));
}

CodePudding user response:

When you send a REST request using fetch() in the browser, the browser doesn't process the response. It's up to your code to look at the status code and body of the response and take any action that you need to. The browser will not change the URL based on the response.

My recommendation is to use 200 to indicate that the login was successful, and then in the browser code, navigate to /auth. In your server code, you should send a 500 status instead when there's an error.

To simulate a redirect, your best bet is to use location.replace (see How do I redirect to another webpage? for a discussion on why):

window.location.replace('/auth.html')
  • Related