简体   繁体   中英

IONIC can't set token

I am trying to send post request so I am retrieving my stored token but I cannot use it in my request function it return [object object]

Code

token: any; //to be used in post request

  constructor(
    private http: HttpClient,
    private env: EnvService,
    private storage: NativeStorage,
  ) {
    this.storage.getItem('token').then((token) => {
      this.token = token; //set token value
      console.log('token', token); // will get the token in console
    }); 
  }

  store(
    name: String,
    description: String,
    phone: String,
    province_id: String,
    kota_id: String,
    address: String,
    logo: String,
    banner: String,
  ) {
    const headers = new HttpHeaders({
      'Accept': 'application/json, text/plain',
      'Content-Type': 'application/json',
      'Authorization': 'Bearer' + " " + this.token //return [object object]
    });
    console.log('header', headers);

    return this.http.post(this.env.STORES_URL,
      { name: name, description: description, phone: phone, province_id: province_id, kota_id: kota_id, address: address, logo: logo, banner: banner }, { headers: headers }
    )
  }

PS: I've commented each part so you can understand better where the problem comes from.

any idea?

Update

I've been playing with this code and if I use

'Authorization': 'Bearer' + " " + JSON.stringify(this.token)

I will get something like:

Authorization: Bearer {"success":{"token":"eyJ0eXAiOiJK....

Still need to go to step forward into token array {"success":{"token":"

Any idea now?**

Update 2

regarding to comment request here is how my token stores in storage (when user loggin)

login(email: String, password: String) {
    return this.http.post(this.env.BASE_URL + '/login',
      { email: email, password: password }
    ).pipe(
      tap(token => {
        console.log(token);
        this.storage.setItem('token', token)
          .then(
            () => {
              console.log('Token Stored');
            },
            error => console.error('Error storing item', error)
          );
        this.token = token;
        this.isLoggedIn = true;
        return token;
      }),
    );
  }

I've a similar problem and was because an issue of asyncronity.

I solved like this:

A function to get the token (in a class named global :

getToken() {
    return this.storage.get(this.token_key);
  }

Then a function to create the headers:

async getHeaders() {
    const httpOptions = {
      headers: new HttpHeaders({
        'Content-Type': 'application/json',
        'Authorization': 'Bearer ' + await this.global.getToken()
      })
    };
    return httpOptions;
  }

And when I call the post :

async post(route, postdata){
    this.http.post(route, postData, await this.getHeaders());
}

Hope it helps!

Local storage only supports string datatype.

So when storing the token in local storage, convert the object to string using JSON.stringify() :

this.storage.setItem('token', JSON.stringify(token));

And when reading the token from local storage, convert back from string using JSON.parse() :

this.storage.getItem('token').then((token) => {
      this.token = JSON.parse(token); //set token value
      console.log('token', token); // will get the token in console
}); 

SOLVED

Based on Update 1 in my question now i can get my token like this code and my problem is solved.

'Authorization': 'Bearer' + " " + this.token.success.token

There was no need of JSON.stringify() or JSON.parse()

Thanks for all helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM