Menachem Hornbacher
Menachem Hornbacher

Reputation: 2165

Ionic http requests with authorization headers

I am sending a get request to the server and it requires a JWT token to authenticate. However Ionic insists on doing a pref-etch request without one and crashing. (Also is there any way to capture non 200 responses? the server gives a lot of those (e.g. 403 {message: Account Invalid}))

Code

auth.ts

import { Headers, RequestOptions } from '@angular/http'
import 'rxjs/add/operator/toPromise';
...
export const getToken = function(http){
    return new Promise((resolve, reject) => {
        let headers = new Headers();
        headers.append('Content-Type', 'application/x-www-form-urlencoded');
        headers.append('Authorization', 'JWT eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjU4Yzg1MmI1YmQ1NjE1MGJkMDAxZWEzNyIsImlhdCI6MTQ4OTY3ODE0NywiZXhwIjoxNDg5NjgxNzQ3fQ.zUWvBnHXbgW20bE65tKe3icFWYW6WKIK6STAe0w7wC4');
        let options = new RequestOptions({headers: headers});
        http.get('//localhost:3000/auth/users', {headers: options})
        .toPromise()
        .then(res => resolve(res))
        .catch(err => console.log(err));
    });
}

Chrome console:

Response for preflight has invalid HTTP status code 401

Server sees: (I logged out the request and there are no headers or body)

OPTIONS /auth/users 401 25.613 ms - -

Upvotes: 1

Views: 15513

Answers (2)

Menachem Hornbacher
Menachem Hornbacher

Reputation: 2165

To anyone else having this issue. devanshsadhotra's answer is great but here is the way I solved this issue:

ionic.config.json (add all the relevant routes here)

  "proxies": [
    {
      "path": "/api",
      "proxyUrl": "http://localhost:3000/api"
    },
    {
      "path": "/auth",
      "proxyUrl": "http://localhost:3000/auth"
    }
  ]

Your networking file (auth.js in this case)

import { Headers } from '@angular/http'  //Headers need to be in this object type
import 'rxjs/add/operator/toPromise';  //turns observable into promise

export const getToken = function(http){  //passing in the Http handler to the function for no good reason. but it works
    return new Promise((resolve, reject) => {  //return a promise to the calling function so it can handle the response
        let headers = new Headers();
        headers.append('Content-Type', 'application/x-www-form-urlencoded');
        headers.append('Authorization', 'JWT eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjU4Yzg1MmI1YmQ1NjE1MGJkMDAxZWEzNyIsImlhdCI6MTQ4OTY4MjY2MywiZXhwIjoxNDg5Njg2MjYzfQ.tW8nT5xYKTqW9wWG3thdwf7OX8g3DrdccM4aYkOmp8w');
        http.get('/auth/users', {headers: headers}) //for post, put and delete put the body before the headers
        .toPromise()  //SANITY!!!
        .then(res => resolve(res)) //Things went well....
        .catch(err => console.log(err)); //Things did not...
    });
}

Upvotes: 1

Devansh sadhotra
Devansh sadhotra

Reputation: 1625

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { Toast, Device } from 'ionic-native';
import { Http, Headers } from '@angular/http';     
let headers = new Headers();
      headers.append('Token', this.Token);
      headers.append('id', this.ID);

      this.http.get(this.apiUrl + this.yourUrl, { headers: headers })
        .map(res => res.json())
        .subscribe(
        data => {
          console.log(data);
          if (data.code == 200) { // this is where u r handling 200 responses
            if (data.result.length > 0) {
              for (let i = 0; i < data.result.length; i++) {
                var userData = {
                  username: data.result[i].username,
                  firstName: data.result[i].firstName,
                  lastName: data.result[i].lastName,
                }
                console.log(JSON.stringify(userData));
                this.Results.push(userData);
              }
            }


          }
          else { // here non 200 responses
            console.log(data.message);
          }

          this.user= this.Results;

          console.log(this.user);
        },
        err => {

          console.log("ERROR!: ", err);
        });

this way u will be able to handle all responses from backend

I hope this works for you

Upvotes: 8

Related Questions