Ajwad Majed
Ajwad Majed

Reputation: 11

fetch() API with NodeJS server makes req.redirect() not working

I have a login/signup system using nodeJS. now the problem is when i use fetch() method on the client javascript side the res.redirect() method does not work. what could be the problem with fetch() API thats stopping the res.redirect method on the server.js ? the last line does not work the res.redirect('/index.html');

maybe there is another way to submit my form on the client javascript without using the fetch() method?

here is my code for my client javascript

const MyForm = document.getElementById("myform"); const username = document.getElementById("username") const email = document.getElementById("email"); const password=document.getElementById("password"); const confirmPassword = document.getElementById("confirm-password-input"); const alertMessege = document.getElementById("message");

MyForm.addEventListener('submit' , function(event) { event.preventDefault();

MatchingPassword();
});
function MatchingPassword(){
let pass = password.value.trim();
let confpass = confirmPassword.value.trim();
if(pass != 0) {
    if(pass  == confpass){
        alertMessege.textContent = "";
        console.log("Password Match");
       
        fetch('SignUp.html' , { 
            method: 'POST',
            headers:{
                'content-Type': 'application/json',
            },
            body: JSON.stringify({
                username: username.value,
                email: email.value,
                password: password.value,
            }),
        });
        console.log("Fetched and posted");
    }
    else{
        alertMessege.textContent = "Password doesn't match! ";
        console.log("Password Does not Match!");
    }


}
}

and here is the server.js the last line does not work the

res.redirect('/index.html');

that is in this piece of code

// app.post sign up form  
app.post("/SignUp.html", async function(req, res){ const {username, email, password} = req.body;

let user = await UserModel.findOne({email});

if (user){
    console.log("User Already Exists");
    return res.redirect("/SignUp.html");
}
 user = new UserModel({
     username, 
     email,
     password,
 });

 await user.save();

 console.log(user)

 res.redirect('/index.html');
});

my html body

<body>
 <form id="myform" action="SignUp.html" method="POST"> Create an account <div class="card"> <div class="card-body">
           
 <!-- full name  input-->
            <div class="form-group">
                <label for="fullname-input">Full name</label>
                <input type="text" class="form-control" id="username" placeholder="Enter full name" name="username" maxlength="50" required>
            </div>
            

          <!-- email  input-->
          <div class="form-group">
            <label for="email-input">Email address</label>
            <input type="email" class="form-control" id="email" aria-describedby="emailHelp" placeholder="Enter email" name="email" pattern="^[\w]{1,}[\w.+-]{0,}@[\w-]{2,}([.][a-zA-Z]{2,}|[.][\w-]{2,}[.][a-zA-Z]{2,})$" title="Must be a valid email. [email protected]" required>
          </div>
        
         <!-- password  input
              minimum set to 8 chars(must have one letter,one number and a symbol)
        -->
          <div class="form-group">
            <label for="password-input">Password</label>
            <input type="password" class="form-control" id="password" placeholder="Password" name="password" pattern="(?=.*\d)(?=.*[!@#\$%\^&\*])(?=.*[A-Za-z]).{8,}" title="Password must be at least 8 characters and at least one number, one letter and one symbol" required>
          </div>

           <!--Confirm password must match password input-->
           <div class="form-group">
            <label for="confirm-password-input">Confirm password</label>
            <input type="password" class="form-control" id="confirm-password-input" placeholder="Confirm password" required>
          </div>
          
          <div>
              <small id="message"> </small>
          </div>
          

          <br>
          <input type="submit" class="btn btn-primary btn-block" id="sign-up-button" value="Register">
          <br>
          <p>Already have an account? <a href="./index.html">Sign In</a> </p>
        </div>

      </div>

      
      </form>

</body>

Upvotes: 1

Views: 1227

Answers (1)

OULAHTAK
OULAHTAK

Reputation: 501

the fetch api is not capable to change your browser url, that is why you should redirect on the front-end rather than the backend

on your back-end instead of:

 res.redirect('/index.html')

use

res.json({success : true}) //if signup successfully

and on the front end just add some callback functions to your fetch

fetch('SignUp.html' , { 
            method: 'POST',
            headers:{
                'content-Type': 'application/json',
            },
            body: JSON.stringify({
                username: username.value,
                email: email.value,
                password: password.value,
            })
        })
        .then(result => result.json())
        .then(data => {
            if(data.success)
            window.location.href = "/index.html"
         })

Upvotes: 2

Related Questions