Establishing global HTTP headers in AngularJS

Is it possible to configure the headers for $httpProvider without using

angular.module('myApp', []).config()
?

After logging in the user, I receive an Auth-Token from the server that needs to be included as a HTTP Header in all subsequent requests.

Answer №1

To implement default headers in Angular 1.0.x, you can use the following code:

$http.defaults.headers.common['Authentication'] = 'authentication';

For Angular 1.1.x+, you can utilize a request interceptor with this code:

myapp.factory('httpRequestInterceptor', function () {
  return {
    request: function (config) {

      // To replace existing headers
      config.headers = {'Authentication':'authentication'}

      // To add without replacing existing headers
      // config.headers['Authorization'] = 'authentication';

      return config;
    }
  };
});

myapp.config(function ($httpProvider) {
  $httpProvider.interceptors.push('httpRequestInterceptor');
});

Keep in mind that factories/services act as singletons, so make sure you don't need to change the 'authentication' value dynamically after instantiation.

Answer №2

$http.defaults.headers.common['Authorization'] = 'token';

It appears that the setHeaders() function standardizes the key names.

Answer №3

Expanding on the insights provided by @Guria and @Panga

config.headers['X-Access-Token'] = $window.sessionStorage.token;

An alternative method is to utilize x-access-token in the header as a JWT (jsonwebtoken). I personally save the JWT in the session storage upon initial user authentication.

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

No search results found for Mongoose text search query

Despite using Mongoose 5.7.8 for my app, the text search feature is not yielding any results. Below is a schema/model example: import mongoose, { Document, Schema } from 'mongoose'; import { Moment } from 'moment'; import { IUser } fr ...

Is it possible to embed HTML code within JavaScript strings?

Is my approach to inserting HTML into a JavaScript string correct? In particular, I want to insert an HTML link into a div tag using JavaScript. Here is the HTML: <div id="mydivtag"></div> And here is the JavaScript code: document.g ...

Which method of loading website images is quicker: sequential or parallel, utilizing Javascript?

As I work on developing an AJAX image gallery that preloads multiple large images ranging from 120kB to 2MB before the lightbox appears, a question arises: should these images be loaded sequentially (waiting for one to preload at a time) or in parallel? Wh ...

Revamp your search experience with Algolia's Angular Instant Search: Design a personalized search box template

Custom Search Box Request: My goal is to implement an autosuggest search box using Algolia Angular instant search with an Angular Material design. To achieve this, I am planning to customize the search box component by replacing the standard <ais-sea ...

What are the security benefits of using Res.cookie compared to document.cookie?

When it comes to setting cookies to save data of signed in members, I faced a dilemma between two options. On one hand, there's res.cookie which utilizes the Express framework to set/read cookies on the server-side. On the other hand, there's d ...

MongoDB failing to populate data for NodeJS server request

I have developed an application that sends POST request data to a NodeJS server in JSON format. The content is structured as follows: {"encrypteddata": "someencryptedvalueofthetext"}. This information is stored in a MongoDB database. I have created two f ...

The jQuery each function in combination with the index function allows for

I'm struggling to make this jQuery script work properly: $(document).on('knack-scene-render.scene_126', function() { $('#view_498 > div.kn-list-content.columns.is-multiline').each(function(index) { if ($(this).eq(inde ...

The browser unexpectedly cancelled the ajax call triggered by the beforeUnload event

Seeking advice on a web application that needs to save user input data through an ajax call when they leave the site. Currently using "Fetch" in a beforeunload event listener, but encountering issues with browsers cancelling the ajax call (specifically th ...

Refining Flask-Generated Table Content with jQuery Filters

I'm currently attempting to render a Jinja2 template that showcases an HTML table and enables dynamic filtering to search through the table content. Unfortunately, I'm facing issues with getting the search functionality to work properly. While th ...

Is there a way to adjust a simple program using Discord.js where the setTimeout within a for-loop can print values sequentially instead of simultaneously?

Here is the code I'm using: for (let i = 0; i <= 5; i++) { delay(i); } function delay(i) { setTimeout(() => console.log(`${i} is the number`), 2000); } The output I'm currently getting after 2 seconds is: 0 is the number 1 is the ...

Dreamweaver seems to struggle to properly execute the identical code

There are times when I transfer javascript code from jsfiddle to Dreamweaver and find myself frustrated. Two documents with seemingly identical javascript don't function the same way. In document A, I have this code: <script> alert('test& ...

The component "SafeAreaViewRN" could not be located within the UIManager

Upon attempting to open a bundle on my Android device, I encountered the following error message: A warning was displayed stating that the app was accessing a hidden field in android's view accessibility delegate. Additionally, an Invariant Violati ...

Delay loading external JavaScript within an AngularJS controller by utilizing lazy loading

For certain routes, I need functionality from external JS files but I don't want to load them all at once. Each route requires different JS (e.g. /upload needs photo uploading JS, /photos needs lightbox JS, /funny needs animation JS, etc). What is th ...

Tips on rotating a 3D shape using axis in three.js

Help needed with rotation in three.js I am facing a challenge when trying to rotate a 3D cube in one of my games. //initialize geometry = new THREE.CubeGeometry grid, grid, grid material = new THREE.MeshLambertMaterial {color:0xFFFFFF * Math.random(), sha ...

The error message "TypeError: undefined is not an object (evaluating '_reactNative.Stylesheet.create')" occurred in a React Native environment

I've been working on a project in React Native and have successfully installed all the necessary dependencies. However, upon running the code, I encounter the following error message: TypeError: undefined is not an object (evaluating '_reactNativ ...

"Latest version of ThreeJS (r160) utilizes ShaderMaterial to render textures

I've been attempting to incorporate a texture into this shader, but it's displaying as black. I suspect there's a small detail I'm overlooking, despite my search yielding no relevant information for ThreeJS version r160. The shader code ...

Is Socket.io combined with Redis the best architecture for an interactive gaming experience?

My current setup involves a NodeJS scaling architecture with Redis, specifically designed for a real-time multiplayer game. However, I'm facing challenges in configuring separate lobbies for players, as the load balancer assigns users to different ser ...

Navigating using TypeScript with React Navigation

When it comes to navigating in my app, I rely on useNavigation from '@react-navigation/native'; This is how I transfer data between two screens: type UserDetailsProps = { onDeleteContact: (id: number) => void; route: any; }; I'm try ...

Tips on utilizing Phonegap to showcase directory located in sdcard

I am currently working on an android-based Phonegap application using the ionic framework and I am trying to figure out how to display all the files in the SD card directory using Phonegap. I have tried using the Phonegap file API, following a tutorial l ...

Learn the process of transforming JSON data into an array with the structure provided

Struggling to fetch data from a Firebase Realtime database and pass it into Google Spreadsheets as JSON objects. Any help would be greatly appreciated. Here is the structure of my Firebase Realtime database: { "4rjF1iwudEXEevtzEoGwDrEtEpI3": { " ...