Search code examples
restionic-frameworklaravel-5ionic3ionic-view

POST data ionic 3 and backend API restful laravel


I have an issue about POST data at add student page. I'm using ionic 3 and backend API restful laravel, I tried this POST in postman and it's works, but I got an error message "invalid token or token not provided" after click Add button (refer the first picture). I'm not sure how to write method with auth token.

You can refer my provider (second image) ,addstudent.ts (third image), button html (forth image) for reference

Thanks in advance.


Solution

  • Suppose you stored your token in a storage (e.g localStorage or sessionStorage), you can do the following:

    Step1: Add Auth provider and extend BaseRequestOptions

    import { BaseRequestOptions, RequestOptions, RequestOptionsArgs } from '@angular/http';
    import { Injectable } from '@angular/core';
    
    @Injectable()
    export class AuthProvider extends BaseRequestOptions {
    
      constructor() {
        super();
        this.headers.set('Content-Type', 'application/json');
      }
    
      merge(options?: RequestOptionsArgs): RequestOptions {
    
        let newOptions = super.merge(options);
        let accessToken = localStorage.getItem('accessToken');
        if (accessToken !== null && accessToken !== undefined) {
          let token: AcessTokenResponse = JSON.parse(accessToken);
          newOptions.headers.set('Authorization', token.token_type + ' ' + token.access_token);
        }
    
        return newOptions;
      }
    }
    

    Step2: Add AuthProvider under providers in app.module.ts file