Ionic 4: Setting native http post headers properly

206 Views Asked by At

I'm struggling to find the solution to my problem with ionic native http.

I tried the answer to this post, but still i am getting the same error

this is my code

switchToggle(){

   let url = 'https://io.adafruit.com//api/v2/myusername/feeds/my-feed-id/data/';

   const headers = new Headers();
   headers.set("Content-Type", "application/json")
   headers.set("X-AIO-Key", "PASTED_MY_KEY_HERE");

   let data = {
            "datum":{
              "value" : 1
            }
          };
   this.http.setDataSerializer('json');

   this.http.post(url,data,{headers:headers})
   .then(data => {
       console.log(data);
   }).catch(error => {
     console.log(error)
   });
}

and this is the error I am getting

enter image description here

when I try other post request without headers it is working fine. But for this specific API I need to send the request together with the headers.

1

There are 1 best solutions below

0
On

set your header like this =>

  setHeaders() {
    let headers = new Headers();
    headers.append("X-AIO-Key", "PASTED_MY_KEY_HERE");
    headers.append('Content-Type', 'application/json' );

        const requestOptions = new RequestOptions({ headers: headers });
        return requestOptions;
      }

  switchToggle(): Observable<any>{
          let data = {
            "datum":{
              "value" : 1
            }
          };
         return this.http.post(url, data, this.setHeaders())
       .map(Response => Response.json())
          .catch((error: any) => Observable.throw(error.json().error || 'Server error'));
  }