Sach
Sach

Reputation: 83

Getting JSON response with 400 bad request in Angular 2

Im trying to call REST API of Magento 2 from Angular 2.

Facing this issue from very long and really need a fix on the same or atleast suggestion on where the issue is?

Below is how im calling REST from Angualar:

@Injectable()
export class ProductService {
public _productUrl = 'http://10..../Mage_ang2/index.php/rest/V1/customers/1';

constructor(private _http: Http) { }

getProducts(): Observable<IProduct[]> {
let headers = new Headers({ 'Content-Type': 'application/json; charset=utf-8' });
headers.append('Authorization', 'Bearer ntthnrbj1uam2tuv1ekva7n8jh18mcnkby3');
let options = new RequestOptions( {method: RequestMethod.Get, headers: headers });


console.log(headers);
    return this._http.get(this._productUrl,options)
        .map((response: Response) => <IProduct[]> response.json())
        .do(data => console.log('All: ' +  JSON.stringify(data)))
        .catch(this.handleError);
}

When i post the same in Postman, i get a response.

When i run through Angular2, with same headers, I get a JSON response but with 400 (Bad Request) !

Also the response doesnt come to actual request call.

enter image description here

enter image description here

Upvotes: 2

Views: 4137

Answers (3)

Vishal Chauhan
Vishal Chauhan

Reputation: 1

try

const headers = new Headers({ 'Content-Type': 'application/json', 'Authorization': 'Bearer ntthnrbj1uam2tuv1ekva7n8jh18mcnkby3' });    

let options = new RequestOptions({ headers: headers });

return this._http.get(this._productUrl,options)

Upvotes: 0

Malatesh Patil
Malatesh Patil

Reputation: 4665

I have been using same syntax in my sample application but without authorization header. Everything seems correct.

The issue may with setting authorization header. Check the authorization token for correctness.

Try this syntax for setting headers

let headers = new Headers({ 'Content-Type': 'application/json; charset=utf-8';Authorization: **token** });

Upvotes: 1

notnotundefined
notnotundefined

Reputation: 3751

Try this, it should work

 let headers = new Headers({
        'Content-Type': 'application/json',
        'Authorization':'Bearer ntthnrbj1uam2tuv1ekva7n8jh18mcnkby3'
    });

 return this._http.get(url,{headers:headers})
        .map(response: any => {
            return response.json();
        });

Upvotes: 0

Related Questions