Home > OS >  Sending data from expressjs request to form
Sending data from expressjs request to form

Time:04-27

I have a login system where a user enters their information and when they submit it I validate the info with express and if it is not valid i send an error message. Right now i'm just using res.send for the error message, how would i go about redirecting back to my form but having an error message with it. I would prefer not to use url parameters because that is not secure.

CodePudding user response:

So what I understand, is that you want your login form, that show the error message e.g. the password is wrong.

const login = (req, res) => {
    const user = new userModel(req.body.email, req.body.password);
    const found = db.findUser(user);
    if (found) {
        if (user.password == found.password) {
            res.status(200).send(true);
        } else {
            res.status(401).json({ msg: 'The password is incorrect'});
        }
    } else {
        res.status(404).send(false);
    }
};

Then you could use the msg property is the password is wrong in the fetch.

fetch('/api/users/login', {
 method: 'POST'
})
.then(res => res.json())
.then(data => {
document.getElementById('...some div').innerHTML = `<div>${data.msg}</div>`
})
  • Related