Remove header properties from a POST request utilizing the $http service within an AngularJS application

Within my AngularJS application, I am sending a form to a payment gateway. To pass my session token to the backend API, I have included a "Authorization" header field.

However, when attempting to send a request to the payment gateway, an error occurs:

XMLHttpRequest cannot load . Request header field Authorization is not allowed by Access-Control-Allow-Headers.

Coincidentally, the same request works perfectly fine using Postman, returning a 200 status code.

To showcase this issue, I have created a Plunker demo that also receives a 200 status http://plnkr.co/edit/8Ts6s0VDTTUVVC9dbCJC

$http({
    method: 'POST',
    url: authoriseURL,
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
    },
    data: nabPaymentData
}).
success(function (response, status, headers) {
    alert('Success:' + response + ' status:' + status + ' headers:' + headers);
}).
error(function (err, status, headers) {
    alert('Error:' + err + ' status:' + status + ' headers:' + headers);
});

I am curious if there is a way to remove specific header fields for only one POST request?

Answer №1

If you want to selectively remove the auth header for requests to the payment gateway, using an interceptor is a good solution. Here's how you can do it: First, create the interceptor using a factory function. Then, add the interceptor to your Angular configuration.

app.factory('paymentGatewayInterceptor', ['$log', function($log) {
    return {
    // optional method
    'request': function(config) {
      $log.debug(config.url);
      // check if the request is to the payment gateway and remove the auth header
      if(config.url.indexOf('https://transact.nab.com.au') > -1) {
        $log.debug('before removing auth header');
        $log.debug(config.headers);
        delete config.headers.Authorization;
        $log.debug('after removing auth header');
        $log.debug(config.headers);
      }
      $log.debug(config.url);
      $log.debug(config.headers);
      // perform any additional actions on success
      return config;
    },


  };
}]);

app.config(['$httpProvider', function($httpProvider) {
    $httpProvider.interceptors.push('paymentGatewayInterceptor');
}]);

Answer №2

To exclude the Authorization parameter from a single POST request, you can simply define it as undefined:

$http({
  method: 'POST',
  url: authoriseURL,
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded',
    'Authorization': undefined
  },
  data: nabPaymentData
});

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

Unable to proceed with entering subsequent values into the input field after the initial input in reactjs

Issue with login form: Unable to provide second value after entering the first one. The text input field does not allow for entering more than one value before completing the existing entry. import React, { useCallback } from 'react'; import { Te ...

What is the best way to stretch the background image across both the footer and navbar for my app?

Here is the code snippet I am currently working with: <template> <v-app> <AppBar></AppBar> <v-main> <router-view></router-view> </v-main> <Footer></Footer> ...

What could be causing my JavaScript source to fail to load in an HTML document?

Currently, I am in the process of creating a basic offline dinosaur game using HTML, JS, and CSS that is well-known to everyone. I have been diligently working on it and have successfully made everything function for a few hours. However, out of nowhere, m ...

Illustrating an image in React-Admin sourced from a local directory with the path extracted from mongoDB

When pulling data from my mongoDB server, I'm encountering an issue with displaying the image. Everything else shows up correctly, except for the image. <ImageField source='filename' title="image" /> The filename in question ...

How to Handle a TypeError When Deleting a File Using GridFS with Mongoose and Node.js

In the process of developing an application that facilitates uploading and downloading music files, I have encountered a specific issue. While I am able to successfully upload files and send them to clients, I am facing challenges when attempting to delete ...

Manipulating CSS styles with jQuery

Trying to update the UL image in the CSS directory using jQuery for a Twitter stream: as tweets are displayed, want to change the avatar of the account associated with each post. Using .css is straightforward, but struggling to modify the URL for the new i ...

Is there a way to verify whether the value of a parameter sent to a javascript function is null?

On my hands, lies this piece of javascript code: function modifyButtonState(selectionItem, actionType, pictureCategory) { var $selection = $(selectionItem); var $buttonIcon = $(selectionItem + ' icon'); $buttonIcon.re ...

Prevent automatic merging of JSON data with identical IDs

My AJAX call to a PHP select request is as follows: $.ajax({ type: "POST", url: "/renforts/_getIntervenantManager", data: { IDMission : IDMission, IDManager : IDManager }, dataType : 'json' ...

AngularJS Textbox Stacking

Does anyone know how to stack data from other text-boxes into a Text-area using AngularJs? I am looking to create something similar to the tag input field on StackOverflow. ...

Is there a way to match a string with information stored in a JSON file?

I have a snippet in my index.js that looks like this: if ('and' == trueWords) { console.log('Success!') } else { console.log('Failure!') } Below is the content of my json file: { "and": 1 } Appreciate your help! ...

Despite population, MongooseJS still renders blank array

Currently in the process of developing an application using Node.js with MongooseJS as the middleware for handling database operations. Encountering an issue with nested schemas, specifically with one of them being populated incorrectly. Despite tracking ...

The ng-show directive in AngularJS seems to be malfunctioning as the <div> element remains

I'm trying to assign the response data to the $scope, but the div with the ng-show directive remains hidden. I am new to AngularJS, so I'm not sure what's wrong. else { debugger; $scope.exception = data.exception; //the da ...

Guide to integrating custom fields in Wordpress with mapbox-gl js to generate map markers

Currently, I am in the process of generating a map that will display various points using Mapbox and WordPress. To achieve this, I have set up a custom post type within WordPress where the coordinates are stored in custom meta fields. Although the fields h ...

Struggling to locate the element value in Puppeteer? Reach out for assistance with await page.waitForSelector() or await page.waitForXPath()

insert image description here[ await page.waitForSelector('.DateRangeSelectorstyles__DateInput-sc-5md5uc-2.kXffji.sc-cSHVUG.VGFsW'); await page.type('.DateRangeSelectorstyles__DateInput-sc-5md5uc-2.kXffji.sc-cSHVUG.VGFsW','01- ...

Identify modifications in the input and at the same time update another input

I currently have two input text boxes. My goal is to synchronize the content of the second input box whenever the first input box is changed. I attempted to achieve this using this code snippet. However, I encountered an issue where the synchronization on ...

What type of loader is required to manage the output from these loaders?" - What specific loader should be used in this case?

I recently initialized a new react application using the create-react-app command. Upon attempting to utilize a react package by importing its default component, I encountered a compilation error: Compiled with problems: ERROR in ./node_modules/@USER-NAME ...

What are the ways to convert canvas animations into gif or webm formats?

I've written a function to capture each frame for the GIF, but I'm experiencing laggy output and crashes as the data increases. Any recommendations? function generateGifFromImages(imageList, frameRate, fileName, scaling) { gifshot.createGIF({ ...

Update the current value in array.prototype

Recently, I've noticed that the built-in JavaScript sort function can be unreliable at times. To address this issue, I decided to create my own sorting function. Consider the following scenario: Array.prototype.customSort = function(sortFunction, upd ...

Using Node.js to serialize JSON POST data as an array

Looking to retrieve POST data from my front-end form. Upon using console.log(req.body), I receive the following output: [ { name: 'name', value: 'kevin' } { name: 'email', value: '' }, { name: 'phone' ...

Utilizing OrbitControls with Socket.io in a Three.js Sphere

I'm currently troubleshooting an issue with my project. I have a three.js sphere ("HTML1" on Desktop) with controls (THREE.OrbitControls) that is functioning properly on both my computer and tablet. My goal is to control this sphere through my iPad, s ...