2

I am trying to access an API which requires Basic Authorization.

Using Postman or Advanced Rest API Tool, I am able to get the response. However when I'm trying to access through Angular 4 HttpClient I am getting this exception:

login:1 XMLHttpRequest cannot load https://someUrl.com:4400/api/v1/login. 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:4200' is therefore not allowed access. The response had HTTP status code 405.

Here is the angular code

@Injectable()
export class LoginService {

    constructor(private http: HttpClient, @Inject('api') private api) {

    }
    login(post) {

        let auth="Basic "+ btoa(post.username + ":" + post.password);
        console.log(auth);
         let headers = new HttpHeaders({'Content-Type': 'application/json'})
         .set("authorization", auth);
       console.log(headers);
        return this.http.post(this.api + 'login',null,{
        headers:headers
      });
    }
}
Roddy of the Frozen Peas
  • 14,380
  • 9
  • 49
  • 99
  • 1
    Does your api allow cross origin requests? try same origin and see what response you get paste the headers and response here. If possible allow cross origin request and then see repsonse as well. – Farrukh Subhani Aug 07 '17 at 15:57
  • 1
    Yes. cross origin is enabled. I am getting response if I am accessing the api via postman – Pawan Kumar Prasad Aug 07 '17 at 16:00
  • 1
    Here is the request header Accept:*/* Accept-Encoding:gzip, deflate, br Accept-Language:en-GB,en-US;q=0.8,en;q=0.6 Access-Control-Request-Headers:authorization Access-Control-Request-Method:POST Connection:keep-alive Host:hosturl.com:3443 Origin:http://localhost:4200 Referer:http://localhost:4200/login User-Agent:Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36 – Pawan Kumar Prasad Aug 07 '17 at 16:07
  • 1
    I don't think Postman cares about CORS headers (https://stackoverflow.com/a/36486188/398606), so you probably need to double check your CORS config on the server. – Sunil D. Aug 07 '17 at 17:52

0 Answers0