1

I'm using Java Rest API services remotely. They are sending username & password along with services for authorization. Here i'm using angular6 and there is problem with the headers i'm passing. Below is my code

import { Injectable } from '@angular/core';
import { HttpClient,HttpHeaders} from '@angular/common/http';
import { Http, Response } from '@angular/http';
import { Observable, Subject } from 'rxjs';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import { HttpModule } from '@angular/http';
`
@Injectable()

export class MasterService{

constructor(private http:HttpClient) { }

getApi(url): Observable<any> {
let headers = new HttpHeaders();
headers = headers.append('Content-Type', 'application/json');
headers = headers.append("Authorization", "Basic YWRtaW46YWRtaW4=");
headers = headers.append('Access-Control-Allow-Origin', '*');
headers = headers.append('UserName', 'admin');
headers = headers.append('password', 'admin');
return this.http.get(url,{ headers:headers })
  .map((res) => {
    console.log(res);
    return res;
}).catch(this.handleErrorObservable);
}
}
`

I got error like this

OPTIONS http://publicIp/coms/getEnterpriseCutomerDtls?custid=10 401 
(Unauthorized)

Access to XMLHttpRequest at 'http://publicIp/coms/getEnterpriseCutomerDtls? 
custid=10' from origin 'http://localhost:4200' has been blocked by 
CORSpolicy: Response to preflight request doesn't pass access control check: 
No 'Access-Control-Allow-Origin' header is present on the requested 
resource.

Thanks In Advance

  • 1
    Maybe you have to enable CORS on the server... – Guntram Mar 20 '19 at 11:07
  • Possible duplicate of [Response to preflight request doesn't pass access control check](https://stackoverflow.com/questions/35588699/response-to-preflight-request-doesnt-pass-access-control-check) – Igor Mar 20 '19 at 11:08
  • Error messages are returned for a reason. If you google the generic part of it (ie. everything that is *not* specific to your environment like omitting the end points) you will find a lot of links about CORS. Start there. – Igor Mar 20 '19 at 11:09

1 Answers1

0

I had same questions some time ago, see here: angular-2-authentication-headers

On your headers authorization you must have there the user and password already encrypted like this:

headers = headers.append('Authorization', 'Basic ' + btoa(username + ':' + password));

And always make sure your CORS policy is configured correctly on your backend, I had several issues because of it...

Kiril1512
  • 2,522
  • 2
  • 10
  • 30
  • Hi, Thanks for your response.I have already tried that line but it is not working. Just now i go trough the link and found that there is a problem with the OPTION request. I forward this message to my back end team.I think it may help me to get out of this problem. Thanks & Regards – madhubabu Gopisetti Mar 21 '19 at 04:56