wfdrake
wfdrake

Reputation: 21

Making an HTTP get request to an ASP.net Web API with user authentication in an Ionic Angular app

I'm having trouble making an http get request to an ASP.net Web API with user authentication. The goal is to get a JSON file from the API. I'm developing an Ionic Angular app and all I want to do currently is successfully make the get request.

Additional Context -When you visit the api in a browser, it requires a username and password -A NetworkCredential object is used for authentication in C#

Issue When I preview my app (with ionic serve), I get the following errors: -[Error] Preflight response is not successful -[Error] XMLHttpRequest cannot load http://notrealwebsite.com/api/example/3 due to access control checks. -[Error] Failed to load resource: Preflight response is not successful

What I've tried Right now my code looks like this:

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class ApiService {

  httpOptions = {
    headers: new HttpHeaders({
      'Authorization': 'Basic ' + btoa('domain//username:password')
    }),

  }

  constructor(private http: HttpClient) { }

  getTest(id) {
    return this.http.get(`http://notrealwebsite.com/api/example/${id}`, this.httpOptions);
  }
}

Upvotes: 2

Views: 253

Answers (1)

eppsilon
eppsilon

Reputation: 2081

HTTP requests in a browser environment are restricted by a protocol called CORS. Before making your request, the browser will send an OPTIONS request (a "preflight" check) to the same URL to find out if it is allowed access.

The error message about the "preflight response" means that the server did not respond to the OPTIONS request, or it returned a header telling the browser it could not proceed. The browser devtools's Network tab may have more information - usually the preflight request is linked next to your intended request.

You can also send an OPTIONS request to that URL using a tool like curl and check the response for the proper Access-Control headers:

curl -i -XOPTIONS 'http://notrealwebsite.com/api/example/<id>'

Upvotes: 1

Related Questions