Redirect due to a fetch process

I am currently working on a minimalist website using pure JavaScript and the fetch API to interact with a backend powered by Node.js and Express.js. Once the user logs in, a session cookie is generated.

The issue I'm encountering is related to redirecting to a login page if the session turns out to be invalid for any client request. I have attempted to handle this from the server-side by implementing:

res.status(301).redirect("/login.html");

Despite seeing the redirection occur in the developer tools network tab of the browser and observing the download of the 'login.html' file, it appears that the actual navigation to the page does not happen. Could there be something crucial that I am overlooking?

Is there a more efficient way to approach this dilemma? While one option would involve performing an additional check on the frontend before each request and subsequently executing the redirect, I prefer to avoid such verbosity in my code if possible...

Answer №1

If you want to show the content of login.html instead of just downloading it, you can verify if the fetch response was redirected and update the current URL by setting window.location.href to response.url in the following manner:

fetch(*config*).then(res => {
  // Check for redirection and update URL accordingly
  if (res.redirected) window.location.href = res.url;
})

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

Removing a particular value from a cookie using jquery

I'm currently in the process of creating a shopping cart system that allows users to add or remove products from their basket. For each product, I am storing two pieces of information in the product cookie: the product barcode and price. This is wha ...

Creating Bound HTML inside an AngularJS Grid Cell Template

I recently started using angular js and came across a helpful question on Conditional cell template in ui-grid angularjs. It worked perfectly for me, but now I'm curious about how to display HTML elements like a button tag instead of plain text. Whene ...

Using PHP to iterate through an array and output the values within a

Hey there! I have a question about incorporating PHP foreach and echo into JavaScript to make it dynamic. Here is the current static JavaScript code: <script type="text/javascript"> $(document).ready(function(){ $('input[type="checkbox"]&ap ...

Guide on creating an API for updating a field in MongoDB database

Here are the details of my fields. { "_id" : ObjectId("5b7f93224fc3b140983ea775"), "city" : "visakapatnam", "area" : "mvp", "zone" : "zone II", "ward" : "ward I", "status" : false, "createdAt" : ISODate("2018-08-24T05:09:54.279 ...

Combining Django and chartjs to create stacked multiple charts

Hey there! I'm working on a Django application and using Chart.js to create bar charts. I encountered an issue where, after generating a new chart with a button click, the old one still lingers behind when hovering over the new chart. I have a suspici ...

Tips for arranging Bootstrap cards in ReactJS so they wrap to a new line after three have been displayed

In my personal portfolio, there is a dedicated page for showcasing various projects using Bootstrap cards. These projects are fetched from a CardData.js file and then mapped to a ProjectCard component. Ideally, I want to display 3 cards per row with consis ...

Steps for setting the value of a textbox within a bootstrap popover

When a user clicks on an Anchor element, I am displaying a Bootstrap popover using the following JQuery code. Jquery $("[data-toggle=popover]").popover({ trigger: 'click', placement: "top", html: true, ...

Error: Unable to iterate through the {(intermediate value)}. It's not a function

Snippet of the original code: const genreOptions = [{{ genreOptions | json_encode | raw }}].map((type , label) => ({value: type, label: label})); Piece of debugging code: const genreOptions = { "Horror": "Kork ...

Loading indicator displayed at the top of a div using JavaScript/jQuery

My current challenge involves implementing a progress bar, similar to the pace.js progress bar. The issue arises when the browser is refreshed, as the pace.js progress bar loads on top of the body instead of within a specified div. It is important that the ...

using an array as an argument in the filtering function

Is there a way to pass an array to the filter method in JavaScript? I have successfully filtered an array using another array. However, my filter array currently has a global scope. How can I pass the array to make my code cleaner? var array = [1, 2, 3, ...

Perhaps a Boolean condition enclosed in an If Statement nested inside a loop

After reviewing whether a number is prime using the Or Boolean statement, the results are unexpected. Instead of completing the check and returning only prime numbers, the function returns the entire array. function sumPrimes(num) { var arr = []; v ...

jQuery command to display a div element when a button is clicked

Hey there, I'm trying to display a div element in jQuery mobile when the user touches the button. I have already created custom classes for both the button and div element but unfortunately, nothing seems to happen. Can anyone tell me which classes I ...

Conceal the div by clicking outside of it

Is there a way to conceal the hidden div with the "hidden" class? I'd like for it to slide out when the user clicks outside of the hidden div. HTML <!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.c ...

Add JavaScript code to your project without bundling it as a module

Is it possible to incorporate a JavaScript library into webpack that is not structured as a UMD-compatible module (AMD, CommonJS)? I want the library to be included in a <script> tag only when necessary and managed by webpack without passing through ...

Issues with JQuery selectors not properly functioning when used in an external JS file

I have linked the library jquery.peity.min.js and loaded it before anything else. Following that, I am utilizing a function from the above library in my script called myscript.js. Here is an example of how it is used: $(".donut-mult").peity("donut", { ...

Arranging data structures in JavaScript: Associative arrays

I'm facing a major issue. My task is to organize an array structured like this: '0' ... '0' ... 'id' => "XXXXX" 'from' ... 'name' => "XXXX" ...

How to decode JSON data into a JavaScript array and retrieve specific values using index positioning

Upon receiving a json response via ajax, the code looks like this: echo json_encode($data); The corresponding ajax code is shown below: $.ajax({ url:"PaymentSlip/check", data:{val:val}, type: 'POST', succe ...

How come I am able to introduce a new subject, but I am unable to include fresh remarks to the SQLite repository?

I've been developing a forum application that allows users to post comments on different topics. I've successfully implemented the functionality to create, post, and display new topics. However, I'm facing an issue where newly created commen ...

What is the method for altering the icon within the KeyboardTimePicker component in material-ui-pickers?

Is there a way to customize the icon displayed in the KeyboardTimePicker component? I've looked into KeyboardButtonProps and InputAdornmentProps but I'm still unsure of how they can assist me... Link to my customized KeyboardTimePicker ...

Sending information to a Google spreadsheet using JavaScript executed in a web browser

Currently, I am developing a web application that requires the user to be able to upload data directly to their own Google spreadsheet. Initially, I attempted to utilize the Google APIs Client Library for JavaScript but found that it does not include supp ...