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

"Enhancement in Chrome: Inclusion of Origin header in same-origin requests

When we POST an AJAX request to a server running locally, the code looks like this: xhr.open("POST", "http://localhost:9000/context/request"); xhr.addHeader(someCustomHeaders); xhr.send(someData); The webpage where this javascript is executed is also on ...

Iconic slim template for data disabling

Having an issue while working on a Rails app with slim. I am facing a problem passing HTML to slim through a button using the data-disable-with attribute. My aim is to display an icon on the button when it's clicked. = f.submit t("basket.next_step") ...

Monitoring AJAX POST progress with Node.js and Multipart: XMLHttpRequest

Is there a way to provide real-time updates on the size of a file being uploaded to a client, similar to how YouTube does it? I've looked into getting the full size of the file with req.files.myFile.size, but is there a method to track the current siz ...

Is there a way for me to retrieve form information?

I have encountered a challenge with my React app. The login form data appears to be empty when I attempt to send it to the backend. // Login component class submitLoginForm = (event) => { event.preventDefault(); const target = event.target; ...

Merge two separate mongodb records

Just getting started with javascript / express / mongodb. For my initial project, I am working on a simple task manager where todos are categorized by priority - "high," "mid," or "low." However, I am facing an issue when trying to display different entri ...

Running a service in Express.js without being dependent on incoming requests

I have a backend application built using nodeJS and express. The architecture consists of two main files, app.js for handling express configuration, controllers, and MongoDB connection, and index.js strictly for server creation. Now, I am looking to imple ...

Disable browser suggestions in Material UI's Autocomplete component

Encountering an issue with Material-ui Autocomplete: import Autocomplete from "@material-ui/lab/Autocomplete"; Currently using it in: <Autocomplete id="checkboxes-tags-demo" autoComplete={false} options={sta ...

How can you retrieve the index of the outer repeater item within nested ng-repeaters in AngularJS?

If I have multiple ng-repeat loops nested within each other like in the following example: <div ng-repeat="outeritem in outerobject"> <div ng-repeat="inneritem in innerobject" ng-click="function(inneritem.key, $index)"></div> <d ...

Discovering parent elements far up the DOM hierarchy using jQuery

I'm a bit confused about how to locate an element that is a parent element further up the tree. $('.btn-action').hover( function(){ $(this).find('.product-card').addClass('animated bounce'); }, function(){ ...

React checkbox remains checked even after uncheckingIs this revised version

I am currently working on a React application where I display an array of matches as a list of rows. Each row contains two athletes, and users can use checkboxes to predict the winner for each match. Only one athlete per row can be checked. To keep track o ...

Creating a linear video playback system

Having an issue with my code in Chrome where auto play is enabled, but the video won't play. I have a loop set up to play each video one after the other, but first things first - how do I get this video to start playing? If there's a pre-made so ...

Issue encountered in loading css and js folders during the build of the Angular2 application due to the files not being found

I have developed an Angular 2 application that utilizes Node.js server APIs. After building the app using nd b, the files were generated in the dist folder. Where should I specify the production URL for the build so that all CSS and JS files load properly? ...

Showing real-time information from an object

I am attempting to showcase the 'helpText' data on the front end based on the type. Is it feasible to include a conditional statement (metricsType variable) and the [key] value into what I want to return? The final 'p' below provides an ...

Trouble with the query waypoints extension in a simple demonstration

Can anyone help me figure out why the basic example from the waypoints plugin isn't working for me? Here's a link to the jsfiddle I created: http://jsfiddle.net/ZA8bd/2/ CSS .block1 { margin-top:30px; width: 400px; background: red; ...

What steps should I take to enable Google Maps style on mobile devices?

Hi there! I'm having some trouble styling my Google map. Sometimes the style loads correctly in browsers, and sometimes it doesn't. Another issue I've noticed is that when I view the page on mobile platforms like Android Chrome, iOS Safari, ...

Creating PDFs in iOS and Android using Ionic framework

Seeking assistance with resolving this issue. I have researched extensively on Google, jspdf, pdfmake.org, inappbrowser plugins, but have been unsuccessful in getting my Ionic project to function properly. The goal is to create a simple form that includes ...

Getting an error message like "npm ERR! code ENOTFOUND" when trying to install Angular CLI using the command "

Currently, I am eager to learn Angular and have already installed Node version 18.13.0. However, when attempting to install Angular CLI using the command npm install -g @angular/cli, I encountered an issue: npm ERR! code ENOTFOUND' 'npm ERR! sys ...

What steps can I take to reset my JavaScript code once its original purpose has been fulfilled?

I created this code, learning as I went along. It measures Beats Per Minute as one clicks the left-mouse-button each time they feel a pulse. After 10 clicks, the JavaScript code takes all the values in the array and calculates an average BPM. The issue ar ...

ES6 throwing an error: SyntaxError due to an unexpected token ")"

Below is the Node.js script I am working on: pDownload("http://serv/file", "localfile") .then( ()=> console.log('downloaded file successfully without any issues...')) .catch( e => console.error('error occurred while downloading&ap ...

Combining JS Tree and Datatables for Enhanced Functionality

I am facing a challenge on my webpage where I have two columns. The left column consists of a checkbox jstree, while the right column contains a table using datatables. Both the table rows and tree are loaded at the start. My goal is to display a row when ...