1
Hello, I have a serious problem doing an HTTP REQUEST POST when I need to add a custom Header. My Backend API, has some blocked routes and requires authentication via Token, I need to pass it in 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 (thought it could have some relation with CORS) and changed several times my request method using dozens of examples, but nothing yet. :-|
Well, now my code is 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 do two requests, the first it does with the OPTIONS method and then it does the expected REQUEST, see:
My Nodejs API is running with properly configured CORS, I have enabled all HEADERS, METHODS and Origin, for this test, everything is with *. The API is running via ngrok, use the url use in my IONIC REQUEST.
Can anyone explain to me what may be happening and any alternative to solve the case? And why angular/Ionic makes these two requests?
Thank you for the reply Thiago! In the end I was able to find out that the method is correct, I stopped to thoroughly analyze my API and found that my auth was being called in any request. I changed my call to occur only when hitting the expected verb. It was so silly the problem that I spent hours reviewing and recreating. :(
– Daniel Castro