Home > OS >  append header not added in header for api basic auth in ionic
append header not added in header for api basic auth in ionic

Time:02-03

Hi I'm new to ionic and angular a lot of things I still didn't know, i want to send post requests to API with basic auth. here's my code :

import { Component } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http'

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})
export class HomePage {

  constructor(public http:HttpClient) {
    this.call();
  }

call(){
var data = {username:"someusername",password:"somepassword"}
let body = JSON.stringify(data);

let header= new HttpHeaders({
  'Accept': 'application/json',
  'Method': 'POST',
  'Content-Type': 'application/json',
  'Authorization':'Basic ZHJlYW1fMS4wOmRyZWFtXzEuMA==',
});

let options = {headers: header}

this.http.post("someUrl", body, options).subscribe(data =>{
  console.log(data)
}, error => {
  console.log(error);
});

}
}

I'm following a tutorial from this link but looks like I'm using the new version ionic, so I changed a bit by following this post. but I get an error like this.

image error from console log

then I realized, looks like my headers not added to the URL.

image from console.log(options)

and here's an image from console.log(error)

image from console.log(error)

so my question is, how to append header to the URL? if the header is added to the URL will this solve the problem? or maybe I am missing something?

thank you in advance, and sorry for bad grammar English.

CodePudding user response:

Here I have provided a sample code for adding headers for your reference:

import { Component } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http'

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})
export class HomePage {

  constructor(public http:HttpClient) {
    this.call();
  }

call(){
var data = {username:"someusername",password:"somepassword"}
let body = JSON.stringify(data);
const requestHeader = new HttpHeaders()
.set('Authorization', 'Basic ZHJlYW1fMS4wOmRyZWFtXzEuMA==')
let options = {headers: requestheader}

this.http.post("someUrl", body, options).subscribe(data =>{
  console.log(data)
}, error => {
  console.log(error);
});

}
}

CodePudding user response:

I change my library to the new one in ionic 6 documentation (link)

import { HTTP } from '@awesome-cordova-plugins/http/ngx';

constructor(private http: HTTP) {}

...

this.http.get('http://ionic.io', {}, {})
  .then(data => {

    console.log(data.status);
    console.log(data.data); // data received by server
    console.log(data.headers);

  })
  .catch(error => {

    console.log(error.status);
    console.log(error.error); // error message as string
    console.log(error.headers);

});
  •  Tags:  
  • Related