Search code examples
httpcurlionic2xmlhttprequestcouchdb

curl POST works but ionic this.http.post doesn't


I am struggling to get an ionic this.http.post to work.

If I use this curl in my terminal it works great:

curl -v -X POST \
  https://myuser-name:[email protected]:5984/_session \
  -d 'name=app&password=ijF3Ui7VYVbbSejmwsnVVo'

It gives me the following output:

Note: Unnecessary use of -X or --request, POST is already inferred.
*   Trying 37.1.96.50...
* TCP_NODELAY set
* Connected to app.mysite.com (37.1.96.49) port 5984 (#0)
* TLS 1.2 connection using TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384
* Server certificate: app.mysite.com
* Server certificate: COMODO RSA Domain Validation Secure Server CA
* Server certificate: COMODO RSA Certification Authority
* Server auth using Basic with user 'myuser-name'
> POST /_session HTTP/1.1
> Host: app.mysite.com:5984
> Authorization: Basic cDpkTUQySzg0a2lqRjNVaTdWWVZiYlNlam13c25WVm8=
> User-Agent: curl/7.54.0
> Accept: */*
> Content-Length: 52
> Content-Type: application/x-www-form-urlencoded
> 
* upload completely sent off: 52 out of 52 bytes
< HTTP/1.1 200 OK
< Set-Cookie: AuthSession=ZWhzLWFwcDo1OUFENThGRjruBtcPzHcqc1sC9WXrcWI7R27_Mg; Version=1;  Secure; Path=/; HttpOnly
< Server: CouchDB/1.6.1 (Erlang OTP/18)
< Date: Mon, 04 Sep 2017 13:45:35 GMT
< Content-Type: text/plain; charset=utf-8
< Content-Length: 43
< Cache-Control: must-revalidate
< 
{"ok":true,"name":null,"roles":["_admin"]}
* Connection #0 to host app.mysite.com left intact

My ionic POST code looks like this:

  login(callerName:string):any
  // Make sure we have a CouchDB session so that PouchDB can access the CouchDB database
  {
    console.log('Authentication: login(): Login function called from ' + callerName);

    return new Promise(resolve => {
      let headers = new Headers();
      headers.append('Content-Type', 'application/json');

      let credentials = {
        name: COUCHDB_USER,
        password: COUCHDB_PASSWORD
      };

      let result = {
        success: false,
        data: []
      };

      console.log('Authentication: login(): credentials = ' + JSON.stringify(credentials));

      // NOTE:
      //
      // If POST is called with COUCHDB_SERVER with no auth in the url I get the error: Response with status: 401 Unauthorized for URL: https://app.mysite.com:5984/_session"
      //    
      // If POST is called with COUCHDB_SERVER WITH auth in url I get the error: Response with status: 0 for URL: null
      //    This 'might' mean:
      //        Timeout from server
      //        Request not sent
      //        Requesting an unreachable url
      //        ...
      //    This WORKS with curl in terminal
      //
      // With auth in url: https://myuser-name:[email protected]:5984/_session
      // Without auth in url: https://app.mysite.com:5984/_session
      //
      this.http.post(COUCHDB_SERVER + '/_session', JSON.stringify(credentials), {headers: headers})
        .subscribe(res => {
            var details = res.json();
            console.log('Authentication: login(): SuperLogin successful login: res = ' + JSON.stringify(details));

            result.success = true;
            result.data = details;
            resolve(result);
          },
          (err) => {
            console.log('Authentication: login(): Login failed err = ' + err);

            let details = err.json();
            result.success = false;
            result.data = details;
            resolve(result);
          });
    });
  }

If I try the POST in ionic with no auth in the url I get a sensible error message:

Response with status: 401 Unauthorized for URL: https://app.mysite.com:5984/_session"

But if I add auth to the url I get an error message that doesn't tell me what the problem is:

Response with status: 0 for URL: null

I can't work out why it works with curl but not within ionic http.post.

I have the same problem whether I run ionic serve or I run the app on an iPhone.

UPDATE

I have run the ionic App in Chrome and now have a better error:

error: "unauthorized", reason: "Authentication required."

So it is clear I am not getting the POST request correct but can't see why.


Solution

  • The authentication failed in ionic because the usage of this.http.post is incorrect: the second parameter should be HTTP request body object (JSON, the credential object), not a string. Please refer to https://angular.io/guide/http for example.

    The code to send HTTP request would be:

    this.http.post(COUCHDB_SERVER + '/_session', credentials, {headers: headers})...
    

    It works in curl, but not in ionic -- That's because the Content-Type of the HTTP request sent by curl is application/x-www-form-urlencoded, and curl's syntax is correct.

    Shall I add auth to the URL? -- I guess it means the myuser-name:ijF3Ui7VYVbbSejmwsnVVo@ part in the URL. The answer is No: It works in curl (add Authorization header in request) but it won't work in browser, please check Pass username and password in URL for HTTP Basic Auth for details.

    Update: It seems Basic authentication is forced in CouchDB. In order to satisfy it, Authorization header can be added manually in HTTP request:

    headers.append('Authorization', 'Basic ' + window.btoa(username + ':' + password))