angular2 basic authorization on get request – 405

I’m trying to get basic authorization to work for a Get request, but I’m getting 2 exceptions:

OPTIONS http://localhost/drupal/user/1?_format=json

XMLHttpRequest cannot load http://localhost/drupal/user/1?_format=json. Response for preflight has invalid HTTP status code 405

I’m using angular2 with drupal 8 backend

here is my service

var _baseUrl = "http://localhost/drupal";

@Injectable()
export class DrupalService {

  private actionUrl: string;

  constructor(private _http: Http, private _apiUrl: DrupalApi) {

     this.actionUrl = _baseUrl + _apiUrl;
  }

  authHeaders() {

     let username = 'username';
     let password = 'password';

     let token = btoa(username + ':' + password);

     var headers = new Headers();
     headers.append('Authorization', 'Basic ' + token);

     headers.append('Content-Type', 'application/json');
     headers.append('Accept', 'application/json');

     return headers;
  }

  public GetSingle = (id: number): Observable<Response> => {
     return this._http.get(this.actionUrl + id + '?_format=json'
      , {headers: this.authHeaders()}).map(res => res.json());
  }

}

but it works when I try the same request from postman app

enter image description here

how can I fix it?

1
Leave a Reply

avatar
1 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
1 Comment authors
Jason Recent comment authors
  Subscribe  
newest oldest most voted
Notify of
Jason
Guest

In Postman, you are sending a header:

Authorization: Basic bXVyaGFmOmhleGFkZWNpbWFsMDU

But in angular you are passing:

  headers.append('Authorization', 'Basic ' + btoa('bXVyaGFmOmhleGFkZWNpbWFsMDU'));

which will end up being:

Authorization: Basic YlhWeWFHRm1PbWhsZUdGa1pXTnBiV0ZzTURV

So, just don’t convert the string to base64

headers.append('Authorization', 'Basic bXVyaGFmOmhleGFkZWNpbWFsMDU');

Update

Error code 405 means : Method Not Allowed, Which means, drupal does not allow OPTIONS requests. I’ve not worked with Drupal before. But, there should be a way to allow OPTIONS requests.