httpClient - ionic v4

Hi,

After an npm audit fix (may be ?!), http.post not working anymore in ionic but still working in postman and locally

i’m using laravel rest api . I suppose the problem is not here but in my ionic app .
here is the code :
``
login(credentials){

return new Promise((resolve, reject) => {

    const httpOptions = {
      headers: new HttpHeaders({
        'Content-Type':  'application/json'
      })
    };
    let param = JSON.stringify(credentials);
    console.log('param=', param);

    this.http.post(URL, JSON.stringify(credentials), httpOptions)
    // this.http.post('http://localhost:8000/api/login', JSON.stringify(credentials), httpOptions)
      .subscribe(res => {
        let data = res;
        // this.token = data['token'];
        this.storage.set('token', data['token']);
        resolve(res);
      }, (err) => {
        reject(err);
        console.log('from Auth Service : erreur login..............', err);
        
      });

});

}
``

i have a Status Code 401 Unauthorized in log :

Capacitor/Plugin/Console: authentification error {"headers":{"normalizedNames":{},"lazyUpdate":null},"status":401,"statusText":"Unauthorized","url":"*myUrl*","ok":false,"name":"HttpErrorResponse","message":"Http failure response for *myUrl*: 401 Unauthorized","error":{"success":false,"message":"Invalid Email or Password "}}

I can’t figure out what’s happening
Any help will be appreciate, thank you

n

I’m super-confused here.

Your thread title speaks of httpClient: to me that means this critter. If indeed you’re using that, that’s great. I would keep doing that. However, you are instantiating needless promises, doing a bunch of stuff with manual JSONing, and messing with headers that aren’t necessary. Throw all that out and just emulate the idioms in that link above.

However, we’re in the Ionic-Native subforum, which suggests you’re using some other HTTP client. I would suggest not doing that and going back to using HttpClient (which takes us back to the previous paragraph).

But, you say, I need to use the cordova HTTP client because (reason). If (reason) is “I get CORS errors or complaints about insecure connections”, then fix that stuff on the server end and then go back to the first paragraph. Otherwise, please explain what (reason) is.

Thank you @rapropos for your answer. Please, excuse my bad english and certainly my bad knowledge of angular. It’s my first app, read a lot (lot, lot, lot) and learn by myself as i can.

Yes i’m using httpClient from ‘@angular/common/http’, included HttpClientModule from ‘@angular/common/http’ in app module.

Using such config service ( i understand the goal …) for a small app, i think it is not necessary in my case, working alone , both server side and client side, so i know what to submit and how the rest api handle sended data.

Also, i use post method not to add a ressource , just to pass username and password to server in order to authenticate.

Finally i use a promise because the code i pasted is in my authService and i’m injecting authService into another place of the app like this :

this.authService.login(credentials).then( ()=>{ //other stuff here ...
May be i am wrong but i prefer keep code clear and simple in concordance with my knowledge.
app/config/config.service.ts + assets/config.json + app/config/config.component.ts + interface for a typed response + subscribe callback receives data as an Object, and then type-casts it in order to access the properties
It’s too complicated for a simple request post !!

I check my version of android (9), tomorow i’ll try this solution i found on this forum :

<edit-config file="app/src/main/AndroidManifest.xml" mode="merge" target="/manifest/application"> <application android:usesCleartextTraffic="true" /> </edit-config
I let you know about the result.
Thank you

n

“Too complicated”, eh? Here’s how I would write this:

interface LoginRequest {
  username: string;
  password: string;
}

interface LoginResponse {
  token: string;
}

class AuthService {
  constructor(private http: HttpClient) {}
  login(credentials: LoginRequest): Observable<LoginResponse> {
    return this.http.post<LoginResponse>(url, credentials);
  }
}

ok that’s the last part, the other part you omited (cf. documentation you give me the link) you have to create service to store config etc … :

app/config/config.service.ts + assets/config.json + app/config/config.component.ts + interface for a typed response

this is why i said and i still say it’s too complicated for a so simple task .

Anyway, my app is working since one year now, this is why my feeling is this is perhaps a problem of android version ( to confirm) more than my poor code that has been doing the job for all this time

Thank you,

n

Both Google and Apple have been (completely admirably, IMHO) trying to improve user security and, arguably, ensuring the Internet even has a viable future by encouraging people to use HTTPS instead of cleartext HTTP. So if you want to be part of the solution, please please use HTTPS. Adding usesCleartextTraffic makes your app part of the problem instead, and is only delaying the inevitable anyway. If you insist on going down that road, then good luck on your endeavours, but I’m out.

which supposes having an Https rest API , it is not my case and i can’t do anything for this
however I totally agree with you

Sure you could. You could convince whoever is in charge of the backend to add an SSL certificate. You could put up a proxy that has one, and point your Ionic app at that instead.

may be in a wonderfull word… the “whoever” is in another service in another state, i can open a ticket and hope a response :frowning: If i had the autorisation i serve the backend from my personal server at home !
… or doing by my own with what i have

Thank you anyway,

n

Still not working this morning …
I tried cleartext in my xml file :

<edit-config file="app/src/main/AndroidManifest.xml" mode="merge" target="/manifest/application"> <application android:usesCleartextTraffic="true" /> </edit-config>
Here is my env (also i’m using capacitor) :

``
Angular CLI: 7.1.4
Node: 10.9.0
OS: darwin x64
Angular: 7.1.4
… cli, common, compiler, core, forms, http, language-service
… platform-browser, platform-browser-dynamic, router

Package Version

@angular-devkit/architect 0.11.4
@angular-devkit/build-angular 0.13.9
@angular-devkit/build-optimizer 0.13.9
@angular-devkit/build-webpack 0.13.9
@angular-devkit/core 7.1.4
@angular-devkit/schematics 7.1.4
@angular/animations 7.2.15
@angular/compiler-cli 7.2.15
@ngtools/webpack 7.3.9
@schematics/angular 7.1.4
@schematics/update 0.11.4
rxjs 6.3.3
typescript 3.1.6
webpack 4.29.0
``
And the error still the same 401 (Unauthorized) and the Json response is :

{ "success": false, "message": "Invalid Email or Password " }
This response is from my laravel rest API in this part of code :

``
public function login(Request $request)
{
$input = $request->only(‘email’, ‘password’);
$jwt_token = null;

    if (!$jwt_token = JWTAuth::attempt($input)) {
        return response()->json([
            'success' => false,
            'message' => 'Invalid Email or Password: ',
        ], 401);
    }else{
.....

``
Please any help really appreciate !

n

Alléluia !
Keeping the same code, changing nothing except this :

  • remove android folder
  • regenerate it : ionic cap add android
  • sync it : ionic cap sync android

So, it’s solved !

n

1 Like