Utilizing Angular 2 to Access APIs with Basic Security Authentication

I am attempting to make a call to an HTTP method implemented with ASP Web API from an Angular 2 client. However, I am encountering the following error:

OPTIONS 401 (Unauthorized)

XMLHttpRequest cannot load . The response to the preflight request does not pass the access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access. The response returned a HTTP status code of 401.

Below is my implementation, which functions correctly when I disable basic authentication on the IIS Server:

import { Http, Response, Headers, RequestOptions } from '@angular/http';
import 'rxjs/add/operator/map'
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { Entity } from "app/view-models/entity";

@Injectable()
export class HttpService {
    headers;
    options;
    constructor(private _http: Http) {
        this.headers = new Headers();
        this.headers.append('Authorization', 'Basic ' + btoa('username:password'));
        this.headers.append("Access-Control-Allow-Credentials", "true");
        this.headers.append('Content-Type', 'application/x-www-form-urlencoded');
        this.options = new RequestOptions();
        this.options = new RequestOptions({ headers: new Headers(this.headers) });
    }

    public Get = (): Observable<Entity> => {
        var params = '?key=something';
        return this._http.get(environment.apiBaseUrl + environment.getSettings + params
            , this.options)
            .map(response => <Entity>response.json());
    }   
}

Answer №1

It seems like the issue here is more related to CORS rather than Angular/Typescript. The problem appears to be with attempting to make a request from "localhost" to "endpoint". To solve this, you'll need to configure your endpoint service to allow requests from the specified domain.

Read more about enabling cross-origin requests in Web API here.

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

Showing or hiding elements based on user roles in Angular 4

I am currently working on a project that involves multiple user types (SuperUser - SchoolAdmin - Teacher). Each role has specific privileges to access certain elements. How can I dynamically hide elements based on the logged-in user's role using *ng ...

Can you explain the meaning behind the exclamation mark in Angular syntax?

I've noticed this popping up in a few spots lately, but I haven't been able to find any information about it. I'm intrigued by the use of the '!' symbol in Angular syntax. Can anyone explain what it does? https://i.sstatic.net/sj ...

"Trouble accessing the URL" error encountered when trying to load templateUrl for dynamic components in Angular 2

Attempted to modify a solution found here. The modification works well, but when changing the template to templateUrl in the component that needs to be loaded dynamically, an error occurs: "No ResourceLoader implementation has been provided. Can't rea ...

Tips for creating a unit test case for a specialized validator in angular reactive forms

Looking for guidance on creating a test case for this specific method: export class CustomErrorStateMatcher implements ErrorStatematcher { isErrorState(control: FormControl,form:NgForm | FormGroupDirective | null){ return control && control.inval ...

The TSC directive requiring 372 seconds for execution

I recently discovered that my TypeScript Firebase repository, used for cloud functions and consisting of only 6 files in the src directory, was taking an unusually long time to compile when running the tsc command. To investigate further, I executed it wit ...

A step-by-step guide on effectively adopting the strategy design pattern

Seeking guidance on the implementation of the strategy design pattern to ensure correctness. Consider a scenario where the class FormBuilder employs strategies from the following list in order to construct the form: SimpleFormStrategy ExtendedFormStrate ...

When compiling to ES5, TypeScript fails to remove imports

I am working on a TypeScript file that utilizes the moment library, and I need to import moment for it to compile properly. However, after compilation, the import line is still present in the compiled file, which is causing issues on my web page. Here is ...

Tips for implementing [disabled] directive with dual options in Ionic Angular

Check out my page.html code: <ion-content *ngIf="charged"> Order ID: {{order.id_acg}} Item Weight(g): Height(cm): Width(cm): Length(cm): ...

Tips for modifying the width of the mat-header-cell in Angular

Is there a way to customize the mat-header-cell in Angular? I've been trying to change its width without success. Any suggestions would be greatly appreciated. <ng-container cdkColumnDef="name"> <mat-header-cell *cdkHeaderCellDe ...

Should I choose JavaScript or TypeScript for Angular 2.0?

What is the best approach for creating an Angular 2.0 application? Should it be done with JavaScript or TypeScript? I'm struggling to get started with Angular 2.0 using TypeScript, as it's quite different from JavaScript. ...

Acquire the map handler from the service

I'm finding this concept a little tricky to grasp. retrieveLongitudeById(id: number | string) { return this.getHoles().pipe( map(holes => holes.find(hole => hole.id === +id).lng) ); } I want to access this method from my service and incorp ...

How can I activate div elements by clicking on a specific div using Angular 2?

I have created a custom component with search dropdown functionality for selecting dates. <div class="search-dropdown calender-dropdown "> <div class="search-dropdown-tabs-wrp"> <ul class="search-dropdown-tabs"> <li& ...

The 'save' property is not found on the 'IProtein' type. Error code: 2339

Encountering an issue with the mongoose "save" function where the error message reads as "Property 'save' does not exist on type 'IProtein'.ts(2339)". I have come across a solution involving the addition of "extends mongoose.Document" ...

A method to access a stored value in localStorage that does not involve utilizing the __zone_symbol__value property

I am encountering a problem with localStorage. After storing user information in localStorage, I am unable to retrieve it without using the __zone_symbol__value property of the parsed value. This is how I store data into locaStorage localStorage.setItem(& ...

Angular Material 2: Tips for Differentiating Multiple Sortable Tables in a Single Component

Greetings, esteemed members of the Stackoverflow community, As per the Angular Material 2 documentation, it is mentioned that you can include an mdSort directive in your table: Sorting The mdSort directive enables a sorting user interface on the colum ...

I'm interested in creating a unique form validator in Angular that verifies if a string has a combination of letters and numbers. How can this be

Currently, I am developing a registration form within Angular that mandates users to create a password comprising of both letters and numbers. I am in need of embedding a personalized validator to uphold this regulation. What would be the most practical ap ...

When you subscribe to a forkJoin, you will receive an error notification

Trying to determine when all my observables have returned their values is a challenge I'm facing. Here's my approach after including import { Observable } from 'rxjs/Rx';: let observables:any[] = []; observables.push(this.getV ...

Is it possible to utilize a variable within the 'has-text()' function during playwright testing?

With Playwright, I am attempting to locate an element based on the value of a variable For instance: let username = 'Sully' await page.click(`li:has-text(${username})`) However, I encounter the following error: page.click: Error: "has-tex ...

The value is not being found in my form, and the slide-toggle is consistently checked

I am encountering an issue with my forms. On the web, all my slide-toggle options are pre-checked as shown in the image provided. I suspect that the problem lies within the patchFor(){} function. Could someone please review my code for me? I have attempte ...

Tips for properly displaying mathematical equations using MathJax in Angular6

I have successfully loaded mathematical equations using the code below. Now, I aim to integrate it within an Angular environment. How can I convert this code for Angular compatibility? <script src='https://cdnjs.cloudflare.com/ajax/libs/mathjax/2. ...