It is not possible to reroute to an alternative endpoint within the server side using ExpressJS

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

Answer №1

If you are seeing a 304 error in your console, it indicates that the browser is 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);
    });


// To prevent getting a 304 error, make sure to disable the last modified date in your server code

app.disable('etag');

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

angular data binding returning the identifier instead of the content

I have been dealing with managed fields retrieved from a web server in the following format: { "fields":{ "relationshipStatus":[ { "fieldId":4, "name":"Committed" }, { "fieldId":2, ...

I'm encountering an issue with my React master component not being able to locate the

I am having trouble importing a component in my APP.js file. I have been attempting to bring MainComponent into the app.js component, but I am facing difficulties in fetching the component. Any assistance in resolving this issue would be greatly apprecia ...

Display pop-up message in JavaScript

Having trouble with my homework assignment... I can't figure out what's going wrong in my code.. the task is to create a basic math learning tool with level selection feature... I implemented a drop-down menu for selecting the level and arithmeti ...

Node.js causing excessive CPU usage due to repeated gettimeofday calls

Recently, I encountered a situation with a long-running node.js process that would occasionally spike to 100% CPU usage and stop responding to requests. In an effort to diagnose the issue, I used strace to inspect the process and discovered a series of get ...

Error: Trying to use 'loginToday' before it has been initialized

After calling a function from the router that in turn calls another function, I encountered an error: Error: ReferenceError: Cannot access 'loginToday' before initialization router.get('/public', function (req, res, next) { Cedacri ...

Generate a document in MongoDB / mongoose without immediately sending it back

I am facing an issue where a significant amount of server bandwidth is consumed in returning newly created documents back to the caller. This concerns me as it is inefficient use of resources. My goal is to receive only an acknowledgment once the document ...

The function passport.authenticate does not exist / User.findone is not a valid function

**I'm really struggling to figure out what I'm doing wrong. I'm new to passport and JavaScript in general, so any help would be appreciated! Every time I try to run it, I get an error saying 'authenticate is not a function'. Then, ...

Having trouble navigating the maze of Express routing

app.js file // home route app.get("/home", async(req, res)=>{ let allCards = await Card.find({}); let skills = await Skill.find({}); res.render("index", {allCards, skills}); }) // add new skill route app.get("/home/newskill", (req, res)=& ...

Creating unique IDs for movie pages with NUXT using data retrieved from the movie DB API

Here is the breakdown of my folder structure: https://i.sstatic.net/X2CHX.png This showcases how the page appears: https://i.sstatic.net/Zul87.jpg I have successfully retrieved all the necessary data from props. However, I am struggling to comprehend h ...

Angular JS dynamic show/hide script for displaying and hiding dynamic content

Execute the code below as is, it currently works well but I'm looking for a way to achieve the same functionality without cluttering the AngularJS code. <html> <head> <title></title> <script src="https:/ ...

Attempting to test Vuex getters that return undefined when provided with an argument results in an error indicating

Currently, I have set up karma and chai for testing purposes and I am attempting to follow the Testing Getters example available here Below is the code snippet from my fruits.js store: // fruits.js store import Vue from 'vue' import Vuex from & ...

The struggle between Node.js 404 errors and Angular's URL refresh issue

I am currently developing a Node.js and AngularJS application. I encountered an issue where a page loads successfully when the URL is entered, but then I added a script to redirect to a 404 error page. Now, only one of the criteria works at a time - either ...

Is synchronous execution guaranteed by an ajax callback function?

Consider the following scenario: ajaxCall() { $.ajax({ ... ... success: function(response) { event2(); } }); } If we have a sequence of calls like this: event1(); ajaxCall(); event3(); Can we be certain that even ...

What is the functionality of Google Chrome's "New Tab" iframes?

Have you ever wondered about those 8 small iframes displaying your most visited websites? How do they capture snapshots of the websites? How are the websites chosen for display? And most importantly, how do they actually work? Edit: I want to learn how to ...

Implementing as middleware for Server Side Rendering in my multi-language Angular application

While setting up my Angular application with server-side rendering using Express as a middleware, I encountered an issue with internationalization (specifically Spanish and English). To handle this, I prefixed my URLs with /sp and /en to differentiate betw ...

Issue encountered during Firebase deployment: Module '@babel/runtime/helpers/builtin/interopRequireDefault' not found

Struggling to deploy firebase functions and encountering multiple issues. During the deployment process, facing a babel error: Error: Cannot find module '@babel/runtime/helpers/builtin/interopRequireDefault' at Function.Module._resolveFilen ...

What is the best way to execute a JavaScript file with npm scripts?

Trying to use npm but encountering some issues. In my package.json file, I have: "scripts": { "build": "build.js" } There is a build.js file in the same folder that simply console.logs. However, when I execute npm run build I receive the error messag ...

"Utilizing a unified data retrieval system within SWRConfig to manage various request methods

i have set up a SWRConfig with a fetcher. i created some custom hooks: function useData() { const { data, mutate, error } = useRequest('data'); return { data: data, isLoading: !error && !data, isError: error, mutate, }; } ...

Accessing Rails controller information via a JavaScript AJAX request

In the process of developing a rails application, I have implemented code within the controller to interact with an API. Initially, I call the inventories endpoint, followed by separate calls to two other id endpoints (store_id and product_id) in order to ...

Troubleshooting the challenges with jQuery's next().addClass() and prev().addClass() functions

I am attempting to create a slider feature. I have four different contents that I've positioned consecutively, but made them invisible initially. I defined a class called active-client with the attribute display: flex. Using jQuery's addClass() m ...