Tips for ensuring jwt token is not lost when refreshing a page in an angularjs app

My project involves authorizing users using jwt tokens, but I am facing an issue where the token is lost upon page refresh and subsequent requests to the server do not include the token. The setup includes storing the token in local storage and utilizing spring-mvc for the backend. Below is the service I've implemented:

'use strict';
angular.module('authentication')
.factory('AuthenticationService', ['$http', '$localStorage',    
'$rootScope','$route', '$q', function($http, $localStorage, $rootScope, 
$route, $q){
var service = {loggedInUser: function(){
return $q.when($rootScope.user)
}};
service.Login = Login;
service.Logout = Logout;

return service;

function Login(username, password, callback){
    $http.post('http://172.16.0.26:7001/Taisys_Server_Current/auth',
    {username:username, password:password})
    .success(function (response){
        if(response.token){
        $localStorage.currentUser = {username:username,    
        token:response.token};

        $http.defaults.headers.common.Authorization = 'Bearer' + response.token;

        $rootScope.user= $localStorage.currentUser;

        $rootScope.token = response.token;


        callback(true);
      }
      else{
        callback(false);
      }
    });
}
function Logout(){
  delete $localStorage.currentUser;
  $http.defaults.headers.common.Authorization = '';
  $route.reload();
  }
  }]);

Answer №1

In order to proceed, make sure you are logged in.

$http.defaults.headers.common.Authorization = 'Bearer' + $localStorage.currentUser.token;

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

Struggling to make json_encode function properly with input from database

Despite my efforts, I can't seem to get json_encode working properly for results retrieved from the fr column in my database. You can find an export of my table at mctrivia.com/language.zip. I have already switched everything to utf8mb4 as recommend ...

What strategies can be used to manage Error return types in Typescript?

I have a situation where I need to handle either an object of type Person or an Error being returned by a function. My goal is to read the values of keys in the returned object only if it's not an Error. The code snippet below throws an error on the ...

"Troubleshooting: NuxtJs vue-flip feature stuck on front side, not rotating to

I have recently installed the vue-flip plugin in a NuxtJs (VueJS) project that I created using the command: npx create-nuxt-app <project-name>. In the index.vue file, I simply added: <vue-flip active-click="true"> <div slot="front"> ...

What is the standard way to write the server-side code for HTTP request and response handling?

I stumbled upon these resources: How to send HTTP request GET/POST in Java and How to SEND HTTP request in JAVA While I understand the client-side aspect, how can this implementation be done on the server side? The goal is to utilize the link on the clie ...

Problem encountered while using AJAX to load a PHP script, triggered by an onclick event;

My expertise lies in HTML, CSS, JavaScript, and PHP. However, I find myself lacking in knowledge when it comes to jQuery and Ajax. While I work on web design projects involving bars and nightclubs that prioritize style over performance, my current job dema ...

Obtain information from a file containing nested JSON objects in R

I am new to utilizing R for programming and I am currently attempting to parse a file that contains nested JSON objects and convert it into an R dataframe. The file format is structured as follows: { "collect": [{ ... // Data details ...

I attempted to craft a toggle button by applying and removing an active class that I had previously designed, but unfortunately, it did not function as intended

Every time I click on a button, I keep encountering this error message. I am certain that my selector is correct, but I can't seem to figure out why I'm getting the Uncaught TypeError: Cannot read property 'classList' of undefined at HT ...

Executing JavaScript after an ng-repeat in AngularJS has completed can be accomplished by using the

As a beginner in AngularJS, I am trying to utilize the ng-repeat feature to display a list of data. Each item in the list should include a similar structure like <abbr class="timeago" title="2012-10-10 05:47:21"></abbr> after being rendered. A ...

"Discovering the method to showcase a list of camera roll image file names in a React Native

When attempting to display a list of images from the user's camera roll, I utilized expo-media-library to fetch assets using MediaLibrary.getAssetsAsync(). Initially, I aimed to showcase a list of filenames as the datasource for the images. Below is m ...

What is the best way to remove an item from an array?

I'm currently working on implementing a follow/unfollow feature on my page using React/Redux. However, I am struggling to fully grasp how to achieve this. When the user follows 'something', the reducer does the following: case FOLLOW_CITY: ...

Repurposing React key usage

section, I am curious to know if it is standard practice to reuse a React key from one component to another. For instance, in the Row component, the key obtained from the Column component is reused for mapping the children of Row. const Table = props =& ...

Differentiating between an individual array and an array containing multiple arrays

Can jQuery differentiate between a regular array, an array of arrays, and an array of objects? var a = [1,2,3]; var a2 = [[12,'Smith',1],[13,'Jones',2]]; var a3 = [{val:'12', des:'Smith', num:1}]; //a = regular arr ...

How can you utilize jQuery's .post() method to send information as an object?

When I send a .post() request like this var data = $(this).serialize(); $('form').on('submit', function(event) { event.preventDefault(); $.post('server.php', data, function(data) { $('#data').append( ...

JPlayer experiencing technical difficulties on Internet Explorer and Opera browsers

Hey there! I'm facing an issue with my website . I've uploaded some ogg and m4a files for streaming, and while it works perfectly on Firefox, Safari, and Chrome, it's not functioning properly on IE. When I try to play a song, it seems to loa ...

How AngularJS directive within a template can detect routeChangeStart event

I have a directive that is set on an anchor element and checks if the current route matches the link, for example: <a href="/dashboard" data-nav-item="dashboard">Dashboard</a> This directive runs every time the route changes, using $routeChan ...

Ensure accuracy when converting to a float data type

My dilemma involves sending numerical values to a server using an AJAX call. For instance, numbers like 0.77, 100, and similar variations are being transmitted. However, upon reaching the server, the data is being interpreted differently - 0.77 as a double ...

Is it permissible for me to incorporate a package from the dependencies listed in the package-lock.json file into my

I'm looking to incorporate date-fns into my project. I currently have react-datepicker, which also uses date-fns. Can I simply utilize date-fns from react-datepicker, or do I need to install it separately in my project? ...

Creating dynamic URL routes for a static website using Vue

I am facing a challenge with my static site as I am unable to add rewrites through htaccess. Currently, our site is built using Vue on top of static .html templates such as \example\index.html. When I want to create a subpage within this layout, ...

Diving into Angular2 template forms: unraveling the mysteries of the reset function

After going through the template forms tutorial in Angular2, I'm facing a bit of confusion regarding the behavior of the native reset JavaScript function on Angular2 ngModel. While it's not explicitly clarified in the official documentation, my u ...

Error with JSON parsing in node.js

I am attempting to convert the get parameter to JSON using the code below: var query = req.query.query; // query = JSON.parse(query); The value of `req.query.query` is: {'$or': [ { '_id':ObjectId('54ff5ed8d094b1e371fba0 ...