Ionic 3 Http request does not add header authorization

0

Hello, I'm having a serious problem doing an HTTP REQUEST POST when I need to add a custom Header. My API Backend, has some blocked routes and requires authentication via Token, I need to pass it on my Header, however there is no way this works.

I have tried numerous alternatives, since creating an interceptor to add in the Request my Token Authorization, I used the proxy API (I thought it might have some relation with CORS) and I changed my request method several times using dozens of examples, but nothing yet . : - |

Well, now my code looks like this:

import { Component } from '@angular/core';
import { IonicPage, NavController } from 'ionic-angular';
import { HttpClient, HttpHeaders } from '@angular/common/http';

@IonicPage()
@Component({
  selector: 'page-login-home',
  templateUrl: 'login-home.html',
})
export class LoginHomePage {

  constructor(public nav: NavController, public httpClient: HttpClient) {}

  toLogin(){
    var data = {
      user: 'lolo',
      password: 'lololo'
    };

    let url = 'https://lolololo.ngrok.io/auth/v1';

    this.httpClient.post(url, data)
      .subscribe((result: any) => {
        localStorage.setItem('AUTH', result.data.token);
        console.log(result);
      },
      (error) => {
        console.log(error);
      });
  }

  toTest(){

    let data = {};
    let url = 'https://lolololo.ngrok.io/upload/picture';
    let headers = new HttpHeaders({
      'Authorization': 'Bearer ' + localStorage.getItem('AUTH')
    });

    this.httpClient.post(url, data, { headers: headers })
      .subscribe((result: any) => {
        console.log('sucesso ao salvar');
        console.log(result);
      },
      (error) => {
        console.log(error);
      });
  }
}

What I have noticed is that IONIC seems to make two requests, the first one it does with the OPTIONS method and then it does the expected REQUEST, see:

My NodeJS API is running with CORS properly configured, I have enabled all HEADERS, METHODS and Origin, for this test, everything is with *. The API is running via ngrok, I use url usage in my IONIC REQUEST.

Does anyone know how to explain what might be happening and some alternative to solve the case? And why does angular / ionic make these two requests?

    
asked by anonymous 17.09.2018 / 23:30

1 answer

0

The two requests are the default behavior of browsers when using CORS. The browser automatically makes a first request using the OPTIONS method to determine if the request is secure to send, this is called "Preflighted requests". This is done because cross-site requests may have implications on user data.

could you include in the question the contents of the Response tab for the two requests?

    
18.09.2018 / 15:19