Using Ionic to send HTTP requests with authentication headers

I'm encountering an issue with Ionic where it insists on sending a pre-fetch request to the server without a JWT token, causing the app to crash. Additionally, I need a way to capture non-200 responses from the server as it frequently returns errors like 403 {message: Account Invalid}.

Code

auth.js

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 - -

Answer №1

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) { // handling responses with code 200
            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 { // handling non-200 responses
            console.log(data.message);
          }

          this.user= this.Results;

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

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

This approach allows you to manage all backend responses effectively.

I trust this solution will meet your needs.

Answer №2

For those experiencing this issue, devanshsadhotra's solution is helpful, but I approached it in a slightly different way:

In my ionic.config.json file, I included all the necessary routes:

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

In the networking file (in my case, auth.js), I made the following changes:

import { Headers } from '@angular/http'  //Include Headers in this object type
import 'rxjs/add/operator/toPromise';  //Convert observable into promise

export const getToken = function(http){  //Pass the Http handler to the function for no particular reason, but it works
    return new Promise((resolve, reject) => {  //Return a promise to 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}) //Include body before headers for post, put, and delete requests
        .toPromise()  //Ensure stability!!!
        .then(res => resolve(res)) //If everything goes well....
        .catch(err => console.log(err)); //Handle errors...
    });
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

JS The clipboardData in ClipboardEvent is perpetually void

I am trying to retrieve files using CTRL+V from the ClipboardEvent in Angular6, but I am encountering an issue where the clipboardData is always empty regardless of whether I test images or text. This problem persists even when tested on the latest release ...

What is the significance of setting "ResolveJsonModule" to true in the TypeScript compiler options for a node.js project when importing a JSON file?

The title serves as the description. I am curious about the underlying reason behind it. Could you please provide some insight? Thank you. ...

Having trouble retrieving values from radio buttons in Angular 2 forms

Having trouble displaying the values of radio button inputs in Angular 2 forms. ...

Error in Nuxt/TypeScript: Unable to retrieve this - TS2339: Property 'XXX' is not found on type

I encountered an issue while working with Nuxt.js and TypeScript. In my project, I rely on dependencies such as axios or nuxt-i18n. As an example, let's focus on Axios. I followed the configuration outlined in the official documentation for nuxt/axios ...

An issue was encountered in the karma/config.tpl.ts file at line 13, column 18 - a TS1109 error indicating that an expression was expected. This

I'm encountering the following error after updating to Angular 9, so I haven't downgraded TypeScript. Could someone please assist me? I've tried numerous solutions without success. node_modules/karma/config.tpl.ts:66:16 - error TS1005: &apo ...

Differences Between Angular 2 Reactive Forms and Template Forms

We are embarking on a new Angular 2 project and are deliberating on whether to opt for Reactive Forms or Template Forms. If you want to learn more, you can refer to this article: https://angular.io/guide/reactive-forms From what I understand, the main adv ...

Express throwing module errors

I encountered an issue while attempting to expose a REST service in an electron app using expressJS. Following a tutorial, I added express and @types/express to the project. However, when trying to implement a "get" method and running the build with ng bui ...

The redirection code is not being executed when calling .pipe() before .subscribe()

My AuthService has the following methods: signUp = (data: SignUp): Observable<AuthResponseData> => { const endpoint = `${env.authBaseUrl}:signUp?key=${env.firebaseKey}`; return this._signInOrSignUp(endpoint, data); }; signIn = (data: SignIn): ...

The error code TS2345 indicates that the argument type 'Event' cannot be assigned to a parameter type 'string'

Hello, I'm a newcomer to utilizing Angular and I'm struggling to identify where my mistake lies. Below is the TypeScript code in question: import { Component } from '@angular/core'; @Component({ selector: 'app-root' ...

Incorporating a unique variant with Tailwind called "

I'm currently struggling with inputting the configuration file for Tailwind. Despite my efforts, I cannot seem to get it right. The code appears correct to me, but I am unsure of what mistake I might be making. Below is the snippet of my code: import ...

Function arity-based type guard

Consider a scenario where there is a function with multiple optional parameters. Why does the function's arity not have a type guard based on the arguments keyword and what are some solutions that do not require altering the implementation or resorti ...

Exploring Angular: Utilizing URL Parameters for Multiple States

I am curious to know if it is achievable using angular 1.x. The requirement is to create a responsive application that works well on both mobile and desktop devices. Each page of the application should have a ui-view element that shows the regular content ...

Type arguments cannot be accepted in untyped function calls.ts(2347)

My user schema in typescript includes the following interface: interface IUser{ name: string; email: string; password: string; isAdmin: boolean; } Check out the user schema below: const UserSchema = new Schema<IUser>( { name: { type ...

Navigating state and passing data using $state.go, toParams, and $stateParams: A guide

Currently, I am utilizing AngularJS version 1.2.0-rc.2 in conjunction with UI-router version 0.2.0. My objective is to transfer the referrer state to another state, for which I am utilizing the toParams of $state.go as depicted below: $state.go('toSt ...

Tips for updating a selected value without altering the reference value

Encountering an issue with the angular framework when trying to select a value from ng-for loop <tr *ngFor="let dept of department" (click)="clinicChoose(dept)"> <td class="text-center">{{dept.sectionCode}}</t ...

Correctly inputting MongoDB-specific collection methods which are currently defaulting to "any"

I'm facing an issue with typing Mongo collection method responses in my app. Specifically, I am having trouble finding a way to type the response of the deleteMany method. The documented response should look like this: { "acknowledged" : true, "delete ...

Tips for implementing AngularJS tags within Laravel templates

It's common knowledge that Laravel has asset functions in templates, such as: {{ asset('images/148630374252566.gif')}} However, when attempting to use Angular JS variables in a Laravel template, an error is thrown: {{ currentPlaying.title ...

Delete the text in MUI's TablePagination component that displays the number of rows per page and the total rows in the table

Currently, I am integrating MUI's tablePagination component into my React table with TypeScript. I am looking to remove/disable the circlemarked text displayed in the image (the picture is an example from MUI). https://i.stack.imgur.com/ib0t2.png Af ...

The ng-repeat section is not being updated by the data-binding functionality

I'm brand new to using angularjs and I've encountered a data binding complication. My goal is to display a set of mutually exclusive options, represented by images styled with background-image. When an option is selected, the CSS class 'sel ...

"Frustrating issue with Firebase-admin dependency farmhash-modern resulting in webassembly error

Facing an issue while setting up firebase-admin SDK on my nextjs + TS project. Every time I try to call a SDK function, I encounter a webAssembly error. Specifically, when trying to configure a middleware for the server-side API and calling the verifyIdTok ...