To include a request parameter in every HTTP request made with $http in AngularJS

I am looking to utilize Angular's $http service to communicate with an API. However, I need to find a way to save my authorization token within $http so that it is included in every request, whether it is a post, get, put, or delete request. I have observed others placing tokens in the header of the requests, and while I understand how to do this, I am uncertain if it is considered best practice. This is the configuration I currently have:

config(['$stateProvider', '$urlRouterProvider','$http', function($stateProvider, $urlRouterProvider, $http) {
  $urlRouterProvider.otherwise("/view1");

}]);

Answer №1

If you need to communicate with an API that requires token authentication, setting up an interceptor is necessary.

In the configuration file:

function configure(..., $httpProvider) {
    $httpProvider.interceptors.push('authInterceptor');
    ...
}
angular
    .module('app')
    .config(configure);

The authInterceptor is a factory designed to add headers to all $http requests:

function authInterceptor($rootScope, $q, $window) {
    return {
        request: function (config) {
            config.headers = config.headers || {};
            if ($window.sessionStorage.token) {
                config.headers.Authorization = 'Bearer ' + $window.sessionStorage.token;
            }
            return config;
        },
        responseError: function (rejection) {
            if (rejection.status === 401) {
                console.log("Not authorized");
            }
            return $q.reject(rejection);
        }
    };
};

angular
    .module('app')
    .factory('authInterceptor', authInterceptor);

The token can be obtained from sessionStorage, cookies, or any other source.

Answer №2

Setting up configuration for $httpProvider on application initialization!

'use strict';

angular.module('app')
    .config(configHttp);

configHttp.$inject = ['$httpProvider'];
function configHttp($httpProvider) {
    if (!$httpProvider.defaults.headers.get) {
        $httpProvider.defaults.headers.get = {};
    }
    // Disabling IE ajax request caching
    $httpProvider.defaults.headers.get['If-Modified-Since'] = 'Mon, 26 Jul 1997 05:00:00 GMT';
    // Additional settings
    $httpProvider.defaults.headers.get['Cache-Control'] = 'no-cache';
    $httpProvider.defaults.headers.get.Pragma = 'no-cache';
    // Setting User Credential
    $httpProvider.defaults.headers.post['user-credential'] = 'xxxxxx';
}

Answer №3

According to the HTTP specification, the appropriate location for the authorization token is within the headers.

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

Javascript behavior during execution can vary from what is observed during debugging

I'm currently facing an issue while trying to debug a script. Everything seems to work fine in debug mode, but not during runtime. Here's the JavaScript function causing trouble: function Add() { ... $('#Value').val($('#V ...

What is the best way to handle passing the "img" object to an onload event handler in ReactJS JSX?

I am currently working on an img element that I want to be able to listen for the onLoad event. However, I also need access to the image object itself in order to check properties like width and height. Since these images are generated dynamically, I won&a ...

Refresh the Dom following an Ajax request (issue with .on input not functioning)

I have multiple text inputs that are generated dynamically via a MySQL query. On the bottom of my page, I have some Javascript code that needed to be triggered using window.load instead of document.ready because the latter was not functioning properly. & ...

How about sending cookies to different controllers?

We are currently developing a Spring-based application that consists of multiple controllers catering to different modules such as user authentication and analytics jobs. The issue we encountered involves setting cookies in our user controller for authenti ...

Node.js: Steps for receiving an ArrayBuffer in a $http request

I made a request using $http.post from Angular.js to Node.js, expecting to receive an ArrayBuffer. Here is the code snippet: $http.post('/api/scholarships/load/uploaded-files', Global.user, {responseType:'arraybuffer'}).success(functi ...

Utilizing jQuery to remove a class with an Ajax request

My setup includes two cards, one for entering a postcode and another with radio buttons to select student status (initially hidden). An Ajax request validates the postcode input - turning the card green if valid (card--success) and revealing the student se ...

The function signature '(_event: React.SyntheticEvent, value: number) => void' cannot be assigned to the type 'FormEventHandler<HTMLUListElement>'

I am facing an issue with my component "PageFooter" being duplicated in three other components. I am trying to refactor it as a UI component. " I am getting the error message: 'Type '(_event: React.SyntheticEvent, value: number) = ...

The versatility of reusable Backbone components

As I search for the best way to ensure the reusability of Backbone views, I have come across various solutions but am unsure which one would best meet my needs. My goal is to create multiple widgets populated with real-time data and I require a base compon ...

Send a request to the uClassify API using the Node request module

I'm currently working on integrating the uClassify API into my Node project, but I'm encountering some issues with my code. Here's what I have so far: const req = JSON.stringify('Hello, my love!'); const options = { body: ...

Passing form data to PHP using AJAX in CodeIgniter Framework

I'm facing an issue with my HTML structure which is as follows: <form method="POST"> Name : <input id="asgname" type="text"> <br> Description : <input id="asgdescription" type="text"> <br> <a href="#" id=" ...

An issue has arisen with loading chunks in Ionic 5/Angular, possibly due to an un

I am currently working on enhancing the offline capabilities of my Ionic 5 app. To achieve this, I have implemented a strategy where data is stored in SQLite while the app is connected, and then retrieved from SQLite when offline instead of making HTTP req ...

How to incorporate a custom JavaScript file into an Angular 7 application

Suppose there is a JavaScript file named mylib.js in an angular 7 application, located at assets/mylib.js: mylib = function(){ return { hi: function() { alert('hi'); } }; }(); If I want to be able to call mylib.hi() in my hero-f ...

Ways to connect a click event to a dynamically generated child element with the help of jQuery?

I am aware that similar questions have been asked elsewhere, but as someone new to jQuery, I am still struggling to attach a click listener to an a element within a dynamically appended ul.li.a structure in the DOM. Below is an example of how the structure ...

Streaming videos using Flask with a custom template

After successfully implementing the DWA path planning algorithm in C with Python bindings, I have decided to create a web application demo. The concept involves a "robot" following the mouse using DWA, while allowing users to draw walls for objects. My ini ...

Running a script within an Ajax-rendered form using remote functionality in a Ruby on Rails

After clicking the following button, my form is rendered: = link_to 'New Note', new_note_path, :class => "btn btn-primary new-note-button", :type => "button", :id => "new-link", remote: true The form is rendered using the script below ...

What is the best way to apply dynamic wrapping of a substring with a component in Vue.js?

My Objective My goal is to take a user input string and render it with specific substrings wrapped in a component. Specifically, I am looking to identify dates within the string using a regex pattern and then wrap these dates in a Vuetify chip. Progress ...

Issue with Angular Bootstrap DatePicker Directive (Eternicode version) failing to remain in open state

Recently, I've been working on incorporating the Bootstrap Datepicker by Eternicode into my application. To help with this integration, I stumbled upon a directive that utilizes it from this GitHub repository. Migrating the datepicker functionality to ...

Passing intricate data structure from Angular to SignalR

I am encountering an issue when trying to send a complex object to my SignalR hub. The JavaScript object I'm sending matches perfectly with my C# object, so theoretically everything should be functioning correctly. However, for some reason, my UpdateE ...

Using node.js to send custom data over a websocket

I came across an excellent tutorial on websockets. In this tutorial, the server decodes and writes a message to the console whenever it receives a message from the client. After that, the server sends the message back to the client. var firstByte = data ...

Inserting line breaks in the data retrieved through AJAX

Utilizing ajax to transfer data from a sophisticated custom field wysiwyg editor. Within the markup provided, I am specifically addressing the div with the 'bio' class. However, upon receiving the data, it is consolidated into one large paragraph ...