2

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);
  }
}
1

1 Answer 1

1

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>'
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.