I'm encountering an issue with redirecting to a different endpoint. After user registration, I want them to be redirected from /register to /login. I am using Fetch to send form data with POST and receiving it on the server.
Below is my code:
Client-Side Code
// Register function activation upon clicking the register button
document.querySelector("#register_button").addEventListener("click", registerDone);
function registerDone(event){
event.preventDefault(); // prevent default form behavior
// Retrieve information from input fields
const user = {
name: document.getElementById("name").value,
username: document.getElementById("username").value,
email: document.getElementById("email").value,
password: document.getElementById("password").value
};
// Define post method options
const options = {
method:"POST",
headers:{
'Content-Type': 'application/json'
},
body:JSON.stringify(user)
};
// Send data to /register and receive response
fetch("/register", options).then(response => response.json()).
then(data => console.log("Success")).
catch((error) => console.log(error));
};
Server-Side register.js File
router.post('/', async (req, res) => {
console.log(req.body);
try {
const hashedPass = await bcrypt.hash(req.body.password, 13);
await User.create({
name : req.body.name,
username: req.body.username,
email: req.body.email,
password: hashedPass
});
res.redirect('/login');
}
catch(error) {
console.log(error);
res.status(500).send("Internal Server error Occured");
}
});
/register Endpoint Usage in app.js
/* Routes & reference files */
app.use("/", require("./routes/index"));
app.use("/register", require("./routes/register"));
app.use("/login", require("./routes/login"));
What I have attempted:
- Researching for similar issues
- Adjusting placeholders in app.js to "/" and adding register and login routes in the files
- Testing redirection to an actual page
- Reinstalling node_modules package
P.S Getting a 304 status indicating everything is okay, but desired path redirection to localhost:300/login doesn't occur.
P.S 2 Apologies if this question resembles others. Kindly share any existing solutions.
Current Outcome: enter image description here