Titanium alloy and https - titanium-mobile

I am trying to make SSL request, but Titanium keeps rejecting it with a 404 error. The url is correct, here is my code:
exports.APIGetRequest = function(url, callback, errorCallback) {
Ti.API.info('Get Request is called');
var req = Titanium.Network.createHTTPClient({
onload : callback,
onerror : errorCallback,
timeout : 60000,
validatesSecureCertificate : true
});
req.open("GET", url);
console.log("\n\nAPIGetRequest - Alloy.Globals.authToken:\n" + Alloy.Globals.authToken + "\n\n");
req.setRequestHeader('AUTHORIZATION', 'Token ' + Alloy.Globals.authToken);
req.send();
};
Any idea why this is happening?

setting validatesSecureCertificate to true will try to verify CRT if its invalid or expired you will not be able to make request .
set validatesSecureCertificate to false , this will keep httpClient run over https don't worry .
to solve your issue set validatesSecureCertificate to false

Related

How to get each http body updates on angular Http request?

I'm using an express api (my back-end) and an angular app (my front-end).
One express js end point (let's call it '/foo') is processing a lot of files,
i send data using res.write() after each treatment so the http response body is update.
I would like to get this update on my angular app.
I was using ajax in a previous version and it worked fine with ajax call :
xhrFields: {
// Getting on progress streaming response
onprogress: function(e)
{
var progressResponse;
var response = e.currentTarget.response;
if(lastResponseLength === false)
{
progressResponse = response;
lastResponseLength = response.length;
}
else
{
progressResponse = response.substring(lastResponseLength);
lastResponseLength = response.length;
}
actualResponse += progressResponse
}
Unfortunatly i found nothing to get partial http body. I tried to use 'reportProgress' Parameter but it's not working.
For some more context my front-end angular code:
service.ts :
setHolidaysDirectory(holidaysKey: string, path: string): Observable<Object>{
const setHolidayDirectoryStreamHttpRequest =
new HttpRequest('POST', 'http://localhost:8089/holidays/pictures/edit', { 'key': holidaysKey,
'path': path
}, {headers: this._httpHeaders, reportProgress: true, responseType: 'text'});
// pipe stream answer
return this._http.request(setHolidayDirectoryStreamHttpRequest);
}
and my component just call the service and subscribe :
this._holidaysService
.setHolidaysDirectory(key, finalHolidaysForm.path)
.subscribe((stream) => {
console.log('new answer');
console.log(stream);
}, error => console.log(error));
But unfortunatly i got empty answer and all the http body is recovered after res.end() (server side)
Can anyone help pls !
Thank a lot !

ajax responsetext blank/empty in chrome works fine in IE

receiving status = 200 statustext = OK in chrome console
alert "onSuccess" working in IE but not in CHROME
new Ajax.Request("downstocking_apply_async.do", {
onSuccess : function(transport) {
alert("onSuccess");
if (!isHangingRequest()){
initUpdateScanArea(transport.responseText);
}else{
doSuspend();
}},
onFailure : function(transport) {
if (!isHangingRequest()){
document.downstockingForm.action = "downstocking_apply_async.do?" + param;
document.downstockingForm.submit();
}else{
doSuspend();
}
},
parameters : param,
asynchronous : "true"
});
found the solution...custom js library that was imported is creating confusion with prototype js thanks!

ajax request 'Access Control Allow Origin'

I am facing a issue of cross origins. I have googled and found some solutions but they are not working in this case. I wonder why.
I am hosting my application in apache tomcat server. And On the application side I am using XMLHttpRequest for request but I am getting "XMLHttpRequest cannot load http://localhost:8888/systeminfo. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access."
Here is the Application js file
function testget()
{
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
alert(xhr.responseText);
}
}
alert('Getting data');
xhr.open('GET', 'http://localhost:8888/systeminfo', true);
xhr.setRequestHeader('Access-Control-Allow-Origin','*');
xhr.setRequestHeader('Access-Control-Allow-Methods','GET');
xhr.send();
}
I am running node js server on local_host:8888 and sending json response when accessed url like 'http://localhost:8888/systeminfo' .
And here is the json response that I am forming and sending from server
function GetSystemInfo(express)
{
express.namespace('/systeminfo', function(){
express.get('/', function(req, res){
var SYSTEM_INFO = 1;
var jsonres = '{\"event\" : [{ \"apiID\" : \"{0}\" }],\"data\":[{ \"manufacturerName\" : \"MNAME\",\"serialNo\" : \"123456\",}] }'.format(SYSTEM_INFO);
res.setHeader('Access-Control-Allow-Origin','*');
res.send(jsonres);
res.end();
});
});
}
Please Help.
Regards,
Techtotie.

PhoneGap ajax call fails everytime

I am developing a mobile application using PhoneGap, and I have to access some services from another project.
I am using jquery-2.0.0.js and jquery-mobile-1.3.2.js.
$.ajax({
url: 'http://localhost:62465/api/account?email=johndoe#yahoo.com',
dataType: 'json',
success: function (data) {
alert(data.Name);
},
error: function (xhr, type) {
alert("Failed to load data");
alert(xhr + " " + type);
}
});
This ajax call fails everytime. In the config.xml I have the following line: <access origin="*" />
Where I might be going wrong!
The problem is that your phonegap application is requesting a local file from something that isn't a webserver. The local file is delivered with NO HTTP HEADERS - that means no "200 OK" header and no "404 Not Found" errors. So, the status code is assumed to be 0.
Straight javascript XHR will need to ignore status and perform your action on readystate == 4 (finished and ready). Like this:
var myrequest = new XMLHttpRequest();
myrequest.open('GET','localfile.html');
myrequest.onreadystatechange = function(){
if(myrequest.readyState == 4) {
var result = myrequest.responseText;
}
}
myrequest.send();
In MooTools, it's a relatively straightforward task of implementing an altered status test in the Request class - altering the return code test to also accept 0 for true. Like this:
Request.implement({
isSuccess: function(){
var status = this.status;
return ((status >= 200 && status < 300) || status === 0);
}
});
jQuery.... I have some things I'd like to say about jQuery - but I'll hold my tongue because this seems like a classy place.
To prepare jQuery for status == 0, you need to use the always event instead of the success event, you can test the status code there.
$.ajax({
url: '/echo/html/',
type: 'PUT',
data: "email=a#b.com"
}).always(function(data, textStatus, jqXHR){
switch(textStatus) {
case 200:
case 0:
alert('Success.');
break;
case 404:
alert('oops');
break;
}
});
Ajax in Cordova/Phonegap - Yay!
url of your query is localhost, thant means- the same device (android emulator or physical). I'm sure that this is your problem. You should use IP (or domain) of your api json server, maybe 192.168.1.1 (depending on your network configuration)
Are you using a physical device or an emulator ? iOS ? Android ?
I might be wrong, but if you're running your app on a mobile device you can't access to your localhost.
I solved the problem with the "GET" call, but now I am trying to make a "PUT" call and it's the same problem, always fails.
$.ajax({
url: '/echo/html/',
type: 'PUT',
data: "email=a#b.com",
success: function(data) {
alert('Success.');
}
});
If the url: 'http://localhost:62465/api/account?email=johndoe#yahoo.com' is not reachable from your mobile, there's a very useful trick to use.
With www.ngrok.com, you can assign an internet domain to your locally unreachable port.
Just signup, get an access token, and then you can use:
ngrok -authtoken myauthtoken -subdomain=mysubdomainname 62465
And then you can access your computer with the url http://mysubdomainname.ngrok.com/api/account?email=johndoe#yahoo.com
(For people with similiar problems)
Use ajax error to know what is wrong:
error: function(jqXHR, exception){
var msg = '';
if (jqXHR.status === 0) {
msg = 'Not connect.\n Verify Network.';
} else if (jqXHR.status == 404) {
msg = 'Requested page not found. [404]';
} else if (jqXHR.status == 500) {
msg = 'Internal Server Error [500].';
} else if (exception === 'parsererror') {
msg = 'Requested JSON parse failed.';
} else if (exception === 'timeout') {
msg = 'Time out error.';
} else if (exception === 'abort') {
msg = 'Ajax request aborted.';
} else {
msg = 'Uncaught Error.\n' + jqXHR.responseText;
}
console.log(msg);
}

How can I send an AJAX request to a node.js server via HTTPS?

I have the following node.js server set up listening to port 9001
var https = require('https');
var fs = require('fs');
var qs = require('querystring');
var options = {
key: fs.readFileSync('privatekey.pem'),
cert: fs.readFileSync('certificate.pem')
};
https.createServer(options, function (req, res) {
res.writeHead(200);
console.log('Request Received!');
console.log(req.method);
if (true || req.method == 'POST') {
var body = '';
req.on('data', function (data) {
body += data;
});
req.on('end', function () {
console.log(body);
var POST = qs.parse(body);
console.log(POST);
});
}
res.end("hello, world\n");
}).listen(9001);
and I am trying to get this server to respond to an AJAX call
function form_save()
{
console.log("submitted!");
var data_obj = {
data1: "item1",
data2: "item2"
}
$.ajax({
url: 'https://adam.testserver.com:9001/',
type: "POST",
dataType: "json",
data: data_obj,
success: function() {
console.log("success!");
},
complete: function() {
console.log("complete!");
}
});
}
There are two problems occurring with my arrangement. The first is that if I start the server and then click the button that triggers my form_save() the node server does not respond and I get the following error:
submitted!
OPTIONS https://adam.testserver.com:9001/ Resource failed to load
jQuery.extend.ajaxjquery.js:3633
$.ajaxjquery.validate.js:1087
form_savew_worksheet.php:64
confirm_deletew_worksheet.php:95
jQuery.event.handlejquery.js:2693
jQuery.event.add.handlejquery.js:2468
w_worksheet.php:73
complete!
At this point if I access that url directy (https://adam.testserver.com:9001/) I get the expected "hello, world" output as well as the console message "Request Received!
GET". From this point on if I click the button to trigger my AJAX call I get a new error.
submitted!
XMLHttpRequest cannot load https://adam.testserver.com:9001/. Origin
https://adam.testserver.com is not allowed by Access-Control-Allow-Origin.
w_worksheet.php:73
complete!
I don't understand why I get this message as both my form and node server reside on the same server. Thanks for taking the time to read, I appreciate any help I can get on this. I've been stuck for a while now!
You've run into the Cross-Origin Resource Sharing (CORS) specification.
Note the OPTIONS in your output. The OPTIONS HTTP Verb is used by the browser to query the web server about the URL, not to GET its contents or POST data to it.
Your server doesn't respond with the correct header data on a CORS request, so your browser assumes it has no rights to access the data, and refuses to GET or POST to the URL.
If you truly want to let any website in the world run that AJAX request, you can do something similar to the following:
function handleOptions(request, response) {
response.writeHead(200, {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Method": "POST, GET, OPTIONS",
"Access-Control-Allow-Headers": request.headers["access-control-request-headers"]
});
response.end();
}
function server(request, response) {
if(request.method == "POST") {
handlePost(request, response);
} else if(request.method == "OPTIONS") {
handleOptions(request, response);
} else {
handleOther(response);
}
}
https.createServer(sslObj, server).listen(9001);
You can fill in the details and whether you should handle GET separately, and so on (handleOther should return an appropriate error code for each request method you don't support).

Resources