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

Can someone please help me convert this jQuery code into vanilla JavaScript?

My Cordova app has an email sending function that utilizes jQuery. During debugging, the ajax function works perfectly in my browser, but once I build the app and test it on my phone, it stops working. I encountered a similar issue before, which was resolv ...

Implementing Pagination or Infinite Scroll to Instagram Feed

Currently, I am working on creating an Instagram feed for a fashion campaign where users can hashtag their photos with a specific tag. Using the Instagram API, the script will pull all recent posts with this common tag to display on the webpage. Instagram ...

Tips to detect a specific animation completion on an element?

How can I ensure that a specific animation ends when multiple animations are triggered on an element? My scenario involves an overlay song list that appears when a list icon is clicked. The challenge lies in closing the menu smoothly. I have implemented a ...

Using Blob to save CSV file on Safari

Here are the codes I am using to generate a download link for users to download a .csv file from my website. var link = document.createElement("a"); link.id = "csvDwnLink"; window.URL = window.URL || window.webkitURL; var csv = "\ufeff" + CSV, b ...

What is the technique for causing this element to move in reverse?

How can I utilize JS to halt the interval and direct the alien to move backwards once it reaches 700px? I am aware that CSS can achieve this, but I prefer a strictly JS approach. I am struggling with stopping the interval as it hits the left position of 70 ...

Effectively handle multiple connections from nodejs to postgres using the pg library

I need to run a script that performs multiple queries using the pg library for managing connections. However, I am facing an issue where my program stops working when the connection pool is full and does not queue future queries. I have tried setting the p ...

Is it possible to trigger the setState() function of a parent component when a child component is clicked?

Hey there, I'm a new developer diving into the world of Reactjs. I've been working on setting up a Todo app but struggling to configure it just right. My main challenge is getting a button to add items to the list when submitted. I think I'm ...

Finding the way to locate obsolete or deprecated packages in NPM versions

Is there a way to easily identify outdated deep dependencies in the local node_modules folder, separate from the top-level packages? After running the command: npm install with this content in my package.json: "dependencies": { "bluebi ...

Why does the function yield two distinct outcomes?

I can't figure out why, but when I execute the function (kpis1) by itself, it returns the result (100), however, when I run the function (kpis2) alone, I get the result (97). But when I run both functions together, the results are kpis1=100 and kpis2 ...

Ensure that adjacent elements operate independently from one another

The code snippet provided above showcases four components: StyledBreadcrumbs, FilterStatusCode, Filter, LinkedTable. The FilterStatusCode component enables users to input search data using TagInput. If the user inputs numerous tags, this component expands ...

Is it possible to create a mouse-following effect with lighting using Javascript

Recently, I've been honing my Javascript skills and decided to create a follow-mouse function. After successfully implementing it, I started brainstorming a new concept that I'm unsure is achievable. Is there a way to develop an "orb of vision" ...

Exploring the depths of Mongoose queries with recursive parent references

I'm attempting to replicate the functionality of this MongoDB example using Mongoose, but it seems more complicated in Mongoose. Am I trying to force a square peg into a round hole? This source is taken from http://www.codeproject.com/Articles/521713 ...

Do back-end routes get activated when the route path in the URL matches, or when a fetch request is initiated from the front-end?

Exploring the contrast between utilizing a fetch API versus directly visiting the URL corresponding to the route path. Consider a backend route structured as follows: let ALL_RESTAURANTS = [ { id: "0b65fe74-03a9-4b37-ab09-1c8d23189273", name: ...

How do I adjust brightness and contrast filters on a base64 URL?

When presented with an image in base64 format like this: data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAABDAAwfqNRk/rjcYX+PxrV/wtWqwJSTlboMgAAAABJRU5ErkJggg== What is the most efficient method to programmatically alter a filter (such as brightness or cont ...

Performing function in Vue.js when a change occurs

I recently started developing a Vue.js component that includes an input field for users to request a specific credit amount. My current goal is to create a function that will log the input amount to the console in real-time as it's being typed. Ultima ...

The function causes changes to an object parameter once it has been executed

I've encountered an issue with a function that is supposed to generate a string value from an object argument. When I call this function and then try to use the argument in another function, it seems to be getting changed somehow. Here is the code fo ...

How to modify a value in a document within a MongoDB collection

I'm having an issue with updating the 'panel' field in both the cards collection and projects collection. Here is my code snippet: const project = await Project.findOne({"code":currentUser.groupcode}); // this works const ...

Enhancing Grails dynamic dropdown to include a pre-selected value in edit.gsp

One feature I have implemented is a dynamic dropdown menu in my _form.gsp file that appears in both the create and edit pages. While it currently works as intended, I am seeking a way to display the selected value on the edit page. _form.gsp <g:s ...

Utilize external URL in trigger.io's custom UIWebView component

I'm in the process of transitioning my existing backbone application, designed for a native iOS UIWebView, over to trigger.io in order to utilize its image caching and camera access features. The goal is to make this migration quickly and efficiently. ...

Initializing select element with ng-init

This is the code snippet I have implemented for ng-init: <select ng-model="yourSelect3" class="form-control" ng-init="yourSelect3=requirements.Item2[0]" ng-options="yourSelect3.StateName for yourSelect3 in requirements.Item2"> &l ...