How to Get Header Information in Post Request, Ionic 3

Asked

Viewed 509 times

0

Hello, I need to get the Token that returns in Header after I run a POST, I would like to know a way to achieve this, I am using Ionic 3 with Angular. What is the best way to get the Authorization field that the Api returns to me directly from the header?

My code

ionViewDidLoad(){
   this.loginProvider.getToken(this.data, this.headers).subscribe(
     data=>{
        console.log(data); //Aqui eu preciso pegar o header não o body
     }, error=>{
        console.log(error);
     }
   );

It returns null pq the request returns nothing at all, only the token in the header. I don’t know if this behavior is correct.

  • Voce q has backend control?

  • @rafaelphp Yes, I have

  • Then return the token to body and not headers so Oce can pick up the token and save it to your front end and then send the token to the url you need. headers("Authorization Baer token")

  • Voce tmb can create an Intercept and add to your app, so Voce can better handle data requirements

  • @rafaelphp I asked the architect responsible for the API to return the token in body, it turns out I need to implement this hj yet, and it’s an update that we won’t be able to do for now. There is some way to do this by the same header?

  • create an Intercept class watch this video https://www.youtube.com/watch?v=vHoNOpfDdNQ

  • but he probably has to create via body, because I never used any api that in header and always via body, asks him to see about JWT https://jwt.io/introduction/

Show 2 more comments

1 answer

1

Create a class InterceptService to intercept http requests,

// Angular
import { Injectable } from '@angular/core';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, 
HttpResponse } from '@angular/common/http';
// RxJS
import { Observable } from 'rxjs';
import { tap } from 'rxjs/operators';
import { debug } from 'util';
import {ToastrService} from 'ngx-toastr';
import {LoadingService} from '../../../../views/pages/_services/loading.service';

@Injectable()
export class InterceptService implements HttpInterceptor {

constructor(private toast: ToastrService,private loadingService: LoadingService){}

// intercept request and add token
intercept(
    request: HttpRequest<any>,
    next: HttpHandler
): Observable<HttpEvent<any>> {
    // tslint:disable-next-line:no-debugger
    // modify request
    // request = request.clone({
    //  setHeaders: {
    //      Authorization: `Bearer ${localStorage.getItem('accessToken')}`
    //  }
    // });
    // console.log('----request----');
    // console.log(request);
    // console.log('--- end of request---');

    return next.handle(request).pipe(
        tap(
            event => {
                 if (event instanceof HttpResponse) {
                    // console.log('all looks good');
                    // http response status code
                    // console.log(event.status);
                }
            },
            error => {

                this.toast.error(error.message,error.status);
                this.loadingService.waitLoadingClose();
                // http response status code
                // console.log('----response----');
                // console.error('status code:');
                // tslint:disable-next-line:no-debugger
                //console.error(error.status);
                //console.error(error.message);
                // console.log('--- end of response---');
            }
        )
    );
}
}

add the line below in your Module:

providers: [
    InterceptService,
    {
        provide: HTTP_INTERCEPTORS,
        useClass: InterceptService,
        multi: true
    },
],

in his own class InterceptService Voce can take the headers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.