0

Here is my code :

onClick() {
console.log("I am running...");

let headers: Headers = new Headers();
headers.append('Authorization', 'Basic ' + btoa("Userid:password") );
headers.append("Content-Type", "application/json");

let options = new RequestOptions({ headers: headers });
return this.http.get(this.url, options)
  .map((response: Response) => {
    console.log(response);
  }).subscribe();
}

I am getting error : 401 (Unauthorized)

Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8100' is therefore not allowed access. The response had HTTP status code 401.

Kindly provide me some solutions.

  • Its a [CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS) issue.. you have to setup appropriate headers in the server side. Also is this ionic serve? – Suraj Rao Jun 01 '18 at 09:18
  • I am getting response in postman after setting username and password but getting error here –  Jun 01 '18 at 09:30
  • https://stackoverflow.com/questions/36250615/cors-with-postman – Suraj Rao Jun 01 '18 at 09:44

2 Answers2

0

It is a CORS issue. Make sure to have this header on your side AND on the server side too:

headers.append('Access-Control-Allow-Origin' , '*');

(Of course you can specify what you want to allow, the line above is just allowing everything for you)

slashpm
  • 214
  • 2
  • 9
  • why am i not getting unauthorized error when running in postman but getting error while executing application? –  Jun 01 '18 at 09:36
  • because there is no cross-origin request there, I assume :) in postman all such requests work fine but not in the browsers. – slashpm Jun 01 '18 at 09:46
0

Check that your API has CORS setup. Your API needs a options method for CORS preflight check. https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS, https://developer.mozilla.org/en-US/docs/Glossary/Preflight_request.

Christo Goosen
  • 566
  • 4
  • 11