Angular offers the ability to configure HTTP headers for requests

I need to include a header named "access-token" in all of my http requests like this:

var app= angular.module("MainModule", ["ngRoute"]);

app.run(function($http){
    $http.defaults.headers.common['access-token'] =ACCESSTOKEN;
})

and in my service:

 service.get= function (x) {
    console.log(ACCESSTOKEN)
    return $http({
      method: "GET",
      headers: {
        'Content-Type': 'application/json',
        'access-token': ACCESSTOKEN
      },
      crossDomain: true,
      url: GETSERVICE.replace("{id}", x),
      dataType: 'json'
    }).then(function (response) {
      if (response.data) {
        return response.data;
      } else {
        return $q.reject(response.data);
      }
    }, function (response) {
      return $q.reject(response.data);
    });

  }

The issue I am facing is that the header is not visible in the network. Only the OPTION request appears without my desired header.

This is how my backend CORS configuration looks like:


response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE, UPDATE, OPTIONS");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, access-token");

chain.doFilter(req, res);

Any suggestions on how to resolve this?

Thank you.

EDIT 1: Here is the OPTION request without modifying headers


Accept: */*
Accept-Encoding: gzip, deflate, br
Accept-Language: it-IT,it;q=0.9,en-US;q=0.8,en;q=0.7
Access-Control-Request-Headers: access-token
Access-Control-Request-Method: GET
Cache-Control: no-cache
Connection: keep-alive
Host: localhost:8081
Origin: http://localhost:9080
Pragma: no-cache
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36

and with modified headers (worked):


Accept: */*
Accept-Encoding: gzip, deflate, br
Accept-Language: it-IT,it;q=0.9,en-US;q=0.8,en;q=0.7
Access-Control-Request-Headers: access-token
Access-Control-Request-Method: GET
access-token: 1520963789861
Cache-Control: no-cache
Connection: keep-alive
Host: localhost:8081
Origin: http://localhost:9080
Pragma: no-cache
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36

With modified headers, the token is included in the request.

Answer №1

One of the main purposes of CORS is to protect APIs from unauthorized access by random clients.

When using JavaScript to make calls to these APIs, permissions must be granted. Browsers handle most of the workload associated with CORS. However, it is crucial that the server includes certain HTTP headers in response to an OPTIONS request from a client:

Access-Control-Allow-Origin: <Origin fetched from the request>
Access-Control-Allow-Methods: GET, POST, PUT, PATCH, DELETE, DELETE
Access-Control-Allow-Headers: <ACCESS-CONTROL-REQUEST-HEADERS fetched from request>

If this is not possible, code can be implemented on the client side to block all OPTIONS requests, although this comes with security risks:

app.config(['$httpProvider', function ($httpProvider) {
  $httpProvider.defaults.headers.common = {};
  $httpProvider.defaults.headers.post = {};
  $httpProvider.defaults.headers.put = {};
  $httpProvider.defaults.headers.patch = {};
  $httpProvider.defaults.headers.get = {};
}]);

For more information, visit: https://en.wikipedia.org/wiki/Cross-origin_resource_sharing

Answer №2

The preflight request is an OPTIONS request that checks if your client has permission to send a request, especially when CORS (Cross-Origin Resource Sharing) is configured on the server. If the server responds affirmatively, your browser will then automatically send the full request with all the headers you provided.

Answer №3

When it comes to handling HTTP requests in Angular, you can use either the $httpProvider or $http module:

//Using the provider method in the app.config():
$httpProvider.defaults.headers.post['Content-Type'] = 'application/json; charset=utf-8';

//Using the $http instance directly:
$http.defaults.headers.common['Content-Type'] = 'application/json; charset=utf-8';

Answer №4

Alright, let me explain what the issue was.

The friendly individual who developed the REST API that I used for cross-domain requests was checking the token value in the OPTIONS request, leading to a null pointer error.

This problem was resolved by adding a filter specifically for the OPTIONS request.

Thank you for your assistance!

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

What methods are available to change one JSON format into another?

I am receiving JSON data from a Laravel API in the following format: [ { "id":48, "parentid":0, "title":"Item 1", "child_content":[ { "id":49, "parentid":48, "title":"Itema 1 ...

Querying a MySQL database on Google App Engine using Java within the same project

Having a SQL instance named "MySQL 2nd Gen 5.7," I need to execute a simple update query operation from a Google App Engine. The Google App Engine Standard Java Project service has been set up with JDK 1.8, Eclipse Oxygen, Hibernate 3, and classic servlet ...

Swirling hues transforming into #000000 upon second attempt

My goal is to create a button that generates two random color codes. Initially, this button seems to work fine on the first click, but on the second click, both codes turn into #000000. Despite my attempts to troubleshoot the issue, I haven't been ab ...

How can the ordering of dynamically generated components be synchronized with the order of other components?

Currently, I'm delving into Vue 3 and encountering a specific issue. The tabs library I'm using only provides tab headers without content panels. To work around this limitation, I've come up with the following solution: <myTabs/><!- ...

Adding a directive to create a table header

I'm having trouble with an angular directive that is meant to insert a table header. Unfortunately, instead of being placed inside the thead as intended, it ends up outside of the table element. Here's a link to the codepen: http://codepen.io/sac ...

Eliminate file extensions from a URL within an IIS server

Seeking advice on how to create a consistent layout for my web pages that doesn't display the .cshtml tag in the URL. I am using JQuery, JavaScript, HTML, CSS, ASP.net (Web Pages Logic). Example URL: http:// www.site.com/page.htm New to ASP and stil ...

The entry '0-0' already exists for the key 'local_part', please enter a unique value

Creating a simple API to handle GET, POST, DELETE, and UPDATE requests. The GET method is functioning correctly, but encountering an issue with the POST method. When attempting to post data, an error is being encountered: error: Error: ER_DUP_ENTRY: ...

Determine if a group of custom objects in a list all share the same value for a specific property using Java

As a newcomer to Java 8, I am dealing with a list of custom objects of type A. This object is defined as follows: class A { int id; String name; } My goal is to check whether all the objects in this list share the same name. While one way t ...

Avoid displaying the identical div through consecutive random fade-ins and fade-outs

I'm trying to make a JavaScript function that selects a random div from a list of divs, displays it for a few seconds, fades it out, and repeats this process in a loop. The issue I'm facing is that sometimes the same div is selected consecutively ...

Avoid insecurely assigning an any value in TypeScript

Take a look at this code snippet: const defaultState = () => { return { profile: { id: '', displayName: '', givenName: '', }, photo: '', } } const state = reactive(defaultState() ...

Is there a way to direct the user's cursor to a specific location on the page when they hover over an image?

I'm interested in creating a script that can manipulate the user's mouse position when they hover over an image. For example, if I hover over the image, I want the mouse to be dragged lower towards a specific text. Is there a method to achieve th ...

Can an action be activated when the mouse comes to a halt?

Currently, I am having trouble triggering an event when a user stops moving their mouse over a div element. The current event is set up to show and follow another element along with the mouse movement, but I want it to only display when the mouse stops mov ...

Sending data through the backbone form?

Whenever the submit button is clicked, a post request should be made to the server with input data and it will return a JSON object. I am unsure where to define the success function and how to receive the response object. Is this the correct way to call a ...

Incorporating the jQuery UI plugin into Angular for enhanced functionality

I'm exploring options for implementing the jQuery UI layout plugin within an angular application. Are there any existing angular directives that offer similar functionality or achieve the same purpose? ...

Utilizing jQuery to target elements that are dynamically generated upon successful AJAX response

When handling dynamically created elements on ajax success, I encountered an issue. I have multiple checkboxes within a table and when the table content is replaced on ajax success, I am unable to select any new checkbox. While it is possible to trigger cl ...

Is it possible to utilize AJAX to fetch code from a separate file, view, or page in order to create an experience akin to a single-page application

Essentially, I'm aiming to create a simplified version of a Single Page Application within the admin panel of my website. The idea is to organize the information by using tabs, making the panel less cluttered. Here's a rough layout of what I have ...

Looking for the module or file associated with a function handle

When working with NodeJS, how can one identify the file or module where a given function was declared based on its function handle? For instance: // File 1 import { test } from './file1' function fileFile(fn: Function){ //... facing an issu ...

Utilizing AngularJS filtering for deep nested properties

I am looking to implement a filter on nested objects structured as follows: Object 1 : property1 property2 property3 children : Child 1 : propertyChild1 propertyChild2 Child 2 : The challenge I'm facing is t ...

Issue encountered while working with PostgreSQL and Sequelize when using the array_append function

I'm encountering issues with the following code snippet let user = req.user.id; await MyTable.update( {'interested': Sequelize.fn('array_append', Sequelize.col('interested'), user)}, {'where ...

Shifting hues of dots within a grid according to the passing of time

As a newcomer to the world of coding, I have conceptualized an idea for a visually appealing clock. My goal is to visually represent the passage of time throughout the day. To achieve this, I have devised a grid system where each dot on the grid represents ...