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?