简体   繁体   中英

Cannot redirect to a different endpoint in the server side [ExpressJS]

I am having trouble redirecting to a different endpoint. I want after a registration, the user gets redirected from /register to /login. I am using Fetch to send the data from the form, with POST, and receiving it on the server.

My code is as follows:

This is the code on the client-side

    // Activate the register function, when clicking on the register button
    document.querySelector("#register_button").addEventListener("click", registerDone);

    function registerDone(event){
      event.preventDefault(); // prevent the default behaviour of the form

      // Retrieve the information from the 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 the options for the post method
      const options = {
        method:"POST",
        headers:{
          'Content-Type': 'application/json'
        },
        body:JSON.stringify(user)
    };
    // send to /register and retrieve the response
    fetch("/register", options).then(response => response.json()).
    then(data => console.log("Success")).
    catch((error) => console.log(error));
};

Here is my register.js file on the server-side

router.post('/', async (req, res) => {
    console.log(req.body);
    try {
        const hashedPass = await bcrypt.hash(req.body.password, 13); // hashing the password, 13 saltrounds

        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");
    }
// res.redirect('/login'); 
});

And here is where I'm using the /register endpoint in app.js

/*  Routes & reference files */
app.use("/", require("./routes/index")); // require indexjs file
app.use("/register", require("./routes/register")); // require register file
app.use("/login", require("./routes/login")); // require login file

What I have tried

  • Googling and searching for a relative problem
  • Changing the placeholders in the app.js file to "/" and adding register and login to the routes in the files. Didn't work.
  • Redirecting to an actual page, to see if the redirect will work, just got an okay response, with no redirection.
  • Deleting node_modules and installing them again

PS I'm getting a 304 that everything is okay and the path that should be redirected is localhost:300/login ( I can upload a picture if required ).

PS 2 I apologise in advance if this question is similar to others. If there is an answer already, would appreciate to see it.

What I get: enter image description here

If you are getting 304 in the console that means browser caching your response.


const options = {
        method:"POST",
        redirect: 'follow',  //<<<---- add this to option to follow redirection 
        headers:{
          'Content-Type': 'application/json'
        },

fetch("/register", options)
    .then(response => {
        if (response.redirected) {
            window.location.href = response.url;
        }
    })
    .catch(function(err) {
        console.info(err + " url: " + url);
    });


// also in your server code. disable last modified date so it will no longer give you 304

app.disable('etag');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM