Magento – Angular JS2 REST API call with Magento 2 headers not send

apimagento2rest

I try to write code to call Magento 2 API with AngularJS 2

// headers.append('Access-Control-Allow-Origin', '*');
// headers.append('Access-Control-Allow-Headers', 'Content-Type');
// headers.append('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
// headers.append('Content-Type', 'application/json');
// headers.append('Accept', 'application/json');
// headers.append('X-Frame-Options', 'SAMEORIGIN');
// headers.append('Authorization', ' Bearer 3sl175yf8v8pec7hjll9v79mt1w0tvpv');



  // this.createAuthorizationHeader(headers);


  // curl -X GET 'http://www.mageplayground.tk/rest/V1/categories' -H 'Authorization: Bearer 3sl175yf8v8pec7hjll9v79mt1w0tvpv' -H 'Content-type: application/json' -g


  let opt: RequestOptions
  let myHeaders: Headers = new Headers
  // myHeaders.set('app-id', 'c2549df0');
  myHeaders.append('Authorization', 'Bearer 3sl175yf8v8pec7hjll9v79mt1w0tvpv');
  // myHeaders.set('Content-type', 'application/json')

  opt = new RequestOptions({
      headers: myHeaders
  })

  this.http.get('http://www.mageplayground.tk/rest/V1/categories/', opt).subscribe(res => this.result = res);
  console.log(this.result);

i can't send the header of Authorization and i get an error with any header i try to send.

The error i get is 400 .

If i send the get method without headers – i get 401./

When i do curl – i get the parameters and its also work with postman software

i know its not that smart to put my Authorization number but its only a playground so i guess its ok.

Anyone got a solution for me?

Best Answer

I do not test yet. However, we should try:

$http({
    method: 'GET',
    url: '/rest/V1/categories/',
    headers: {
        'Authorization': 'Bearer ' + token
    },
    data: someData
}).then(function successCallback(response) {
    $log.log("Successfully.")
}, function errorCallback(response) {
    if(response.status = 401){
        $log.log("401 Code.")
    }
});

References:

Related Topic