AngularJS is not compatible with Basic Authentication

Need help with setting the header in my JavaScript script

var invocation = new XMLHttpRequest();
        var url = 'http://example.com/api/auth';
        var handler = [];

        if(invocation) {    
            invocation.open('GET', url, true);
            invocation.setRequestHeader('X-PINGOTHER', "DDD");
            invocation.setRequestHeader('Access-Control-Allow-Origin', "http://localhost");
            invocation.setRequestHeader('Access-Control-Request-Headers', true);
            invocation.onreadystatechange = handler;
            invocation.send(); 
          }

The header information from Firebug:

OPTIONS /api/auth HTTP/1.1
Host: example.com
User-Agent: Mozilla/5.0 (Windows NT 6.2; WOW64; rv:18.0) Gecko/20100101 Firefox/18.0  FirePHP/0.7.4
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Origin: http://localhost
Access-Control-Request-Method: GET
Access-Control-Request-Headers: access-control-allow-origin,x-pingother
x-insight: activate
Connection: keep-alive

It always adds to the Access-Control-Request-Headers as value and sets OPTIONS instead of GET. Any suggestions on how to fix this?

Answer №1

When working with AngularJS, it's recommended to utilize the $http service for better results:

$http.defaults.useXDomain = true; //enable cors

$http({
    method: 'GET', 
    url: 'http://website.com/api/auth', 
    headers: {'X-PINGOTHER': 'DDD'}
 });

Answer №2

Success! The code is functioning properly, but not with GET requests. Here's the correct way it should be executed:

$http({
    method: "GET",
    url: "http://example.com/api/auth"
    }).success(function(data) {
        $scope.user = data;
    }).error(function(data) {
        console.log("error");
    });

See a working example below :

$http.jsonp('http://example.com/api/auth?&callback=JSON_CALLBACK')
        .success(function(data){
            console.log(data);
        }).error (function(data){
            alert("eerrror");
        }); 

Keep in mind that it only works with JSONP requests.

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

Ways to change the color of a button when it is both selected and unselected

Currently seeking assistance to implement a feature where clicking on a button changes its color to danger, indicating it is selected. Upon clicking the same button again, it should revert back to its original color, typically primary. This functionality ...

Customized server URL for Angular autocomplete feature

I am interested in utilizing an autocomplete field <angucomplete-alt id="members" placeholder="Search members" pause="400" selected-object="testObj" remote-url="{{remoteUrl}}" remot ...

Error: It is not possible to assign values to properties of an undefined object, specifically the property 'transform'

In this section of my React application, I have implemented a ref.current that is initially set to null. However, I am encountering an issue when trying to change its property. Interestingly, a friend of mine has utilized the same react component, WorkPa ...

What is the best way to activate ui-sref in an AngularJS unit test?

Currently I am conducting a test on an AngularJS view. The code sample contains some non-standard helpers, but they should not affect the specific functionality being tested. Below is the view (written in Jade): #authentication-options button#sign-up(u ...

Determining if a replacement took place in the Javascript replace function

I've developed a function that scans through a set of strings and replaces specific patterns: var content = 'Here is a sample string 1/23'; var currentDate = new Date(); var currentMonth = currentDate.getMonth()+1; var currentDay = curre ...

The getSession provided by the getSession function is accessible within getServerSideProps but appears as undefined within the component

Whenever I try to log the session variable inside the Dashboard component, it comes back as undefined. However, when I log it inside the getServerSideProps function, it returns the correct details. Am I missing something here? Objective: My goal is to fet ...

Fetch data from two interconnected collections in Mongodb using Mongoose's populate feature

I am inquiring about the process of performing a lookup operation in the specified collections. In collection one, the id is used as projectsId in collection two. I have provided the contoller.js and model files below. Can you guide me on where to insert t ...

Patience is key when waiting for Ajax response data in Vue.js

Within my Vue component, I am attempting to retrieve data from an API using axios. <template> <div> This is Default child component {{tools[0].name}} </div> </template> <script> import { CustomJS } fr ...

JS focusing on incorrect entity

Check out the fiddle link below to see the issue: https://jsfiddle.net/0a0yo575/10/ The goal is to display a single box in the top-left corner based on user interaction. However, the current JavaScript is causing the point to disappear instead of the box ...

Locate a div element based on its inner text and then apply a specific

I am looking to target a specific div based on its inner text, and then add a class to it. How can I achieve this? For example, consider the following input: <div>First</div> <div>Second</div> <div>Third</div> The desi ...

Steps for implementing CSS module with a dynamically generated class name

Recently, I started delving into the realm of CSS modules. My current project involves creating a slider that dynamically changes classes like "activeSlide", "nextSlide", and "lastSlide" to achieve different functionalities. However, I'm facing an is ...

How can I retrieve the Azure subscription IDs of the currently logged in user using @azure/msal-angular?

I successfully authenticated a user using @azure/msal-angular and received the id_Token, access_Token and tenant Id. Now I am looking to retrieve the logged in user's azure subscriptions. Is there a way to achieve this through msal or are there any Ja ...

What is the best way to fetch and convert information from an API to display on a website?

I am encountering an issue while trying to retrieve data from an API. Below is my code with a fabricated access code. $(function () { var $data = ('#data'); $.ajax({ type: 'GET', url: 'http://api.openweathe ...

What is the best way to apply the TableRow style in material-ui / mui to make it similar to TableHead?

Trying to implement TableHead styling on TableRow but encountering a warning: validateDOMNesting(...) cannot be a child of. How can this be fixed without triggering a warning message? CollapisbleTableRow.js import React, { Fragment, useCallback } from &ap ...

Is it possible to create an index.html page with all the necessary head tags to prevent duplicate code across multiple html pages?

Imagine I am using app.js or a Bootstrap CDN link for all of my HTML pages, but I don't want to include it in every single page individually. Is there a way to create an index.html file that includes this so that all other HTML pages load the head fro ...

Implementing automatic form saving in AngularJS through sessionStorage as you enter data

I have been attempting to use sessionStorage for auto-saving form data as it is being entered into an input field. However, I am encountering an issue where the data is not being saved. Ideally, when the page is refreshed, the data should still be present ...

All the details from this run are available in the npm run dev log on Ubuntu

Good day! I've been working on deploying a page built in vue.js, and after uploading all the files successfully, I encountered an issue when trying to run "npm run dev." No matter what I try, including re-installing npm dependencies and starting from ...

What is the reason behind having a selectedOptions property rather than just a selectedOption?

Why does the selectedOptions property of select return an HTMLCollection instead of just one HTMLOptionElement? As far as I understand (correct me if I'm wrong), a select element can only have one selected option, so why do I always need to access it ...

The c++ bson extension failed to load, so the pure JS version is being utilized while using monk for Mongodb access

Whenever I try to utilize monk as a middleware for accessing mongodb, I keep getting the following message: Unable to load the c++ bson extension, resorting to pure JS version Here are the specifics of my environment: Operating System: OS X Yosemite No ...

Choose a specific option from the dropdown menu using a URL parameter

After reviewing this code snippet: <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script> // <![CDATA[ $(document).ready(function() { // Parse your query parameters here, and assi ...