Sach
Sach

Reputation: 83

Consumer is not authorized to access angular 2 REST api from Magento 2

Im calling Http requests using Angular with magento 2.

Im using HTTP GET request using my Magento2 REST api endpoint to do the same.

UPDATED:

///<reference path="../node_modules/angular2/typings/browser.d.ts" />
import "rxjs/add/operator/map";
import {Component, Input} from 'angular2/core';
import {Request, Response,Http} from 'angular2/http';
import {Request,Headers,RequestOptions, Response,Http} from 'angular2/http';


interface Person {
    //name: string;
    //age: number;
}

@Component({
    selector: 'my-app',
    template: `<h1>My First Angular 2 App</h1>
    <div>{{people | json}}</div>
    `
})
export class AppComponent {
    @Input() private people: Person[];

 constructor(private http: Http) {
   }

   public ngOnInit() {
    let headers = new Headers({ 'Accept': 'application/json' });
    headers.append('Authorization', 'Bearer x9a278mu7xoh4k0jkj08doc5j4b3ac22');

    let options = new RequestOptions({ headers: headers });
    return this.http.get('http://10.../Mage_ang2/index.php/rest/V1/customers/1',options)
        .map(response => console.log(response.json))
         .subscribe((items: Person[]) => {    //updated
            console.log('items: ' + items);
            this.people = items;
        }, error => console.log(error));
    }
}

On using .subscribe() i get:

app/app.component.ts(32,15): error TS2345: Argument of type '(items: Person[]) => void' is not assignable to parameter of type 'NextObserver | ErrorObserver | CompletionObserver | ((value: void) => void)'. [0] Type '(items: Person[]) => void' is not assignable to type '(value: void) => void'. [0] Types of parameters 'items' and 'value' are incompatible. [0] Type 'void' is not assignable to type 'Person[]'.

XMLHttpRequest cannot load Response for preflight has invalid HTTP status code 400

Upvotes: 0

Views: 993

Answers (1)

digit
digit

Reputation: 4565

You need to set Authorization in the header not send as a query param.

Your http get method :

this.http.get('http://10.12.13.1/Mage_ang2/index.php/rest/V1/products/10090-White-XL?Authorization=Bearer x9a278mu7xoh4k0jkj08doc5j4b3ac22');

Please remove ?Authorization=Bearer x9a278mu7xoh4k0jkj08doc5j4b3ac22 and set the headers as the following

let headers = new Headers({ 'Accept': 'application/json' });
headers.append('Authorization', 'Bearer x9a278mu7xoh4k0jkj08doc5j4b3ac22');

let options = new RequestOptions({ headers: headers });
return this.http
.get('http://10.12.13.1/Mage_ang2/index.php/rest/V1/products/10090-White-XL',options)
.map(res => console.log(res));

and don't forget to import RequestOptions and Headers in your ts file

import {Http, Headers, RequestOptions} from '@angular/http';

Upvotes: 1

Related Questions