How can JavaScript be used to access response header information in Devise Token Auth?

Currently, I am in the process of developing a web application using Rails as the backend API and Vue.js as the frontend library. For authentication purposes, I have integrated the devise_token_auth library. However, I am facing difficulty in retrieving the token information sent inside the header of the response when working with JavaScript.

I discovered alternative libraries such as J-toker, ng-token-auth, angular2-token, etc. After looking into them, I decided to follow jtoker auth because I specifically wanted to integrate it with vue.js. However, I soon realized that it requires React components which was not ideal for my project. Below is a sample response obtained using Postman:

Response Body :

{"data":{"id":3,"email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d2b1bdbca6b3b1a692b6b3a8a8beb7b0bba0b6a1fcb1bdbf">[email protected]</a>","provider":"email","uid":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3a5955544e5b594e7a5e5b4040565f5853485e4914595557">[email protected]</a>","name":null,"image":null}}

Response Header :

Cache-Control →max-age=0, private, must-revalidate
Content-Type →application/json; charset=utf-8
ETag →W/"2af9684eadab13f0efebb27b8e29a7be"
Transfer-Encoding →chunked
Vary →Origin
X-Content-Type-Options →nosniff
X-Frame-Options →SAMEORIGIN
X-Request-Id →41f3df67-574c-4095-b471-a8fd08b85be5
X-Runtime →0.768768
X-XSS-Protection →1; mode=block
access-token →DGoclk9sbb_LRgQrr5akUw
client →7_Lfy0RlEbzkpLOpiQCKRQ
expiry →1516322382
token-type →Bearer
uid →<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="93f0fcfde7f2f0e7d3f7f2e9e9fff6f1fae1f7e0bdf0fcfe">[email protected]</a>

Answer №1

To ensure seamless communication between the client and server, you must intercept all request/response calls to include or retrieve the access-token from the header. Storing configuration headers in the local storage of the browser helps maintain the connection.

One effective way to achieve this is by using a promise-based HTTP client. In the example provided below, we will utilize axios.

Start by importing axios into your Vue application's main.js file:

import axios from 'axios'

You can then set up request interception as follows:

axios.defaults.headers.common['Content-Type'] = 'application/json';
axios.interceptors.request.use(function (config) {
  const authHeaders = JSON.parse(window.localStorage.getItem('authHeaders'));
  if(authHeaders) {
    config.headers[config.method] = {
      'access-token': authHeaders['access-token'],
      'client': authHeaders['client'],
      'uid': authHeaders['uid']
    };
  }
  return config;
}, function (error) {
  return Promise.reject(error);
});

axios.interceptors.response.use(function (response) {
  if(response.headers['access-token']) {
    const authHeaders = {
      'access-token': response.headers['access-token'],
      'client': response.headers['client'],
      'uid': response.headers['uid'],
      'expiry': response.headers['expiry'],
      'token-type': response.headers['token-type']
    };
    window.localStorage.setItem('authHeaders', JSON.stringify(authHeaders));
  } else {
    window.localStorage.removeItem('authHeaders');
  }
  return response;
}, function (error) {
  return Promise.reject(error);
});

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

What is the best way to display a loading image and temporarily disable a button for 3 seconds before initiating the process of sending post data from another page via

Is there a way to display a loading image and disable a button for 3 seconds before sending post data from another page using AJAX POST? Once the OK button is clicked, I would like the loading image to appear and the <input type="button" value="Check" ...

There was an unexpected error in angular.js while trying to work on a calendar widget based on angular-ui-calendar. The error message indicated that the argument 'fn' was expected to be a function but instead received Moment

I came across a similar topic earlier on Stack Overflow, but unfortunately, the issue wasn't resolved. So, I've decided to revisit this question and address it myself this time. In my app.js file, which is where my main module for the app is ini ...

Creating an ongoing loop endlessly using recursion in node.js

Seeking assistance in creating a recursive loop to continuously iterate through functions in Node.js for flow control. I have tried online tutorials but still struggling to comprehend it fully. Can anyone provide guidance or point me towards a proper tutor ...

Oops! Looks like the connection has been abruptly cut off from the ASYNC node

Is there a way to properly close an async connection once all data has been successfully entered? Despite attempting to end the connection outside of the loop, it seems that the structure is being finalized after the first INSERT operation CODE require( ...

The display of Bootstrap Cards may become distorted when incorporating J Query

I am attempting to design a dynamic HTML page that pulls data from a JSON response using an AJAX request. My goal is to display three columns in a row, but currently I am only seeing one column per row. I would greatly appreciate any guidance on what migh ...

Display PDF blob in browser using an aesthetically pleasing URL in JavaScript

Using Node, I am retrieving a PDF from the server and sending it to my React frontend. My goal is to display the PDF in the browser within a new tab. The functionality works well, but the URL of the new tab containing the PDF is not ideal. Currently, the U ...

When an if statement is triggered by an overload of information, it initiates the start of a fresh

I am in need of creating an if statement that will trigger whenever images with IDs 0 to 3 (a total of 4 images) are loaded. This if statement should then generate a new row containing 0 to 3 images, and the same logic needs to be applied for words as well ...

Exploring the Integration of Node Modules with React

I am still learning about Node and I'm struggling to integrate an NPM package with my React project running on Node. Currently, I have a React component that successfully uploads a zip file through Node server scripts. Now, I am working on the next s ...

Vue js parent-child communication using event bus fails to function

Is there any way to successfully communicate between non parent child components in vue js document? I followed the instructions in the vue document, but unfortunately, my code did not work as expected. Below is a snippet of my code: The structure of the ...

Using DIV to "enclose" all the elements inside

I need assistance with my HTML code. Here is what I have: <div id="cover" on-tap="_overlayTapped" class$="{{status}}"> <form method="POST" action="/some/action"> <input required id="name" name="name" label="Your name"></input> ...

You cannot reassign NodeJS global variables

Currently, I am in the process of writing unit tests for code that utilizes a JavaScript library. This particular library sets a global variable if it does not already exist using the following pattern: var GLOBAL_VAR = GLOBAL_VAR || {} While this method ...

Display additional javascript code for expanding a marquee

Currently, I am working on a stock ticker project using JavaScript. It's progressing well, and now I am focusing on adding a "show more" button to style the ticker. The button should be placed outside of the marquee. When clicked, it will expand the m ...

Is it possible to verify an email address using a "Stealthy Form"?

I am exploring the use of HTML5's type="email" validation to develop a function for validating email addresses. My goal is to create a form and add an input that has its type set as email. By attempting to submit the form, I aim to determine whether ...

Press the key to navigate to a different page

I have an input field for a search box. I want it so that when I enter my search query and press enter, the page navigates to another page with the value of the input included in the URL as a query string. How can I achieve this functionality? Thank you ...

Retrieve the HTML content of all children except for a specific child element in jQuery

Is there a way to utilize jQuery/Javascript for selecting the HTML content of the two <p> elements in the initial <div class="description? I'm open to using Regex as well. This specific jQuery selection is being executed within Node.js on a c ...

Limit the execution speed of a JavaScript function

My JavaScript code is set up to trigger a click event when the user scrolls past a specific element with the class .closemenu. This is meant to open and close a header menu automatically as the user scrolls through the page. The problem I'm facing is ...

What could be the reason why my useRouter function isn't working as expected?

I'm currently working on developing an App using nextjs 13 and the new App router feature (https://nextjs.org/blog/next-13-4) : I've encountered a navigation issue despite following the documentation diligently. To illustrate, here's a bas ...

Unable to show <LI> elements

I'm having trouble adding LI items to the #historial <UL> tag. Whenever the for loop is inside the function, the list displays with some elements duplicated. I believe the for loop should remain outside of the function. Could someone please he ...

JavaScript: Dynamically load a script when a particular <a> element is in an active state

<script> function DisplayTag(){ var q1=document.getElementById( 'ctl00_ContentPlaceHolder1_ctl00_ctl00_Showcase' ).childNodes[1].innerHTML; var counter1=0; function executeScript(q1,counter1){ q1= document.getElementById( 'ctl00_Co ...

Event triggered when a text input field becomes active (excluding onfocus) in the FireFox browser

I'm currently working on detecting when a text input field is active. Initially, I used the onfocus event, but I encountered an issue where the onblur event would be triggered when the window was no longer in focus, causing unintended consequences in ...