Search code examples
restappceleratorappcelerator-titanium

Appcelerator Titanium: createHTTPClient fails with same data that works in GUI REST client


REST Client returns "200 OK" - Thats good!

enter image description here

createHTTPClient returns "HTTP error" with the exact same data. When I remove the payoad I get a response, when I add the payload in client.send(payload) I get the error. I do need to pass the payload for future requests.

var payload = { 
    username: 'test',
    password: 'test'
    };

 var url = "https://MYWEBSITE.com/rest_login/user/token.json";

 var client = Ti.Network.createHTTPClient({
     // function called when the response data is available
     onload : function(e) {
         Ti.API.info("Received text: " + this.responseText);
         alert('success');
     },
     // function called when an error occurs, including a timeout
     onerror : function(e) {
         Ti.API.error(e.error);
         alert('error');
     },
     timeout : 5000  // in milliseconds
 });
 // Prepare the connection.
 client.open("POST", url);
 client.setRequestHeader('Content-Type', 'application/json');
 // Send the request.
 client.send(payload);

Solution

  • You just need to change last line to this:

    client.send( JSON.stringify(payload) );
    

    The reason is that since you are setting content-type to application json, so you need to stringify your input data of dictionary object so that server can parse it as per header set.