0

I'm upgrading my Ionic app to version 4 and am running into a weird problem where I'm not sure the data is being properly submitted to my API.

I've stripped this down to about as basic as I can get it and the API still returns a 401 Unauthorized error.

I know the API works, because when I submit the same via Postman I receive the expected data...

I'm importing the HttpClient...

import { HttpClient, HttpHeaders } from '@angular/common/http';

And here's my stripped down function, which runs when the submit button is clicked.

onSubmit() {

    const headers = new HttpHeaders({
        'Content-Type': 'application/x-www-form-urlencoded'
    });

    let body = {
        'username': 'test',
        'password': 'test',
    }

    this.http
        .post(this.apiService.url, body, { headers: headers })
        .subscribe((data: any) => {
            console.log(data);
        }, error => {
            console.log('error');
        });
}

This all worked perfectly in Ionic 3, so I'm really confused as to why it's not working now.

wintech
  • 71
  • 1
  • 9
  • 1
    `where I'm not sure the data is being properly submitted to my API.` <= You need to use the debugging tools in the browser to see what is being submitted. – Igor Jan 07 '19 at 18:45
  • @Igor I've searched quite a bit and haven't been able to find an example of how to view what's being posted in chrome. – wintech Jan 07 '19 at 18:47
  • Have you tried F12? See also https://www.google.com/search?q=view+network+post+in+chrome – Igor Jan 07 '19 at 18:48
  • @Igor Yes, and I'm now seeing it as I had to check `Preserve log`. It looks like it's sending the correct data, but the formatting is all wonky, as I'm seeing a response like this `------WebKitFormBoundaryMbf2rrdvL2QcxoE6 Content-Disposition: form-data; name="username" test` instead of a key/value pair. – wintech Jan 07 '19 at 19:03
  • Check https://stackoverflow.com/q/39863317/1260204, maybe one of these answers helps you? – Igor Jan 07 '19 at 19:05
  • There is some reason to use: 'Content-Type': 'application/x-www-form-urlencoded' instead of 'Content-Type': 'application/json'. – Thomaz Capra Jan 07 '19 at 19:41
  • 1
    @Igor Thank you for that link, it solved it for me :) – wintech Jan 07 '19 at 19:47
  • Possible duplicate of [How to force Angular2 to POST using x-www-form-urlencoded](https://stackoverflow.com/questions/39863317/how-to-force-angular2-to-post-using-x-www-form-urlencoded) – Igor Jan 07 '19 at 19:53

1 Answers1

0

This post solved it for me. Apparently Angular 5+ takes care of the headers for you, so all I had to do was remove them and it worked.

onSubmit() {

    let body = {
        'username': 'test',
        'password': 'test',
    }

    this.http
        .post(this.apiService.url, body)
        .subscribe((data: any) => {
            console.log(data);
        }, error => {
            console.log('error');
        });
}

https://stackoverflow.com/a/47560146/10646827

wintech
  • 71
  • 1
  • 9