File creation works from localhost but not from mobile - javascript

I am trying to send a file creation request to a remote RESTful API.
Whenever I do this from a local server, it works fine. Whenever I do this from an iOS device, it fails with a CSRF validation failed error. As far as I can tell, that shouldn't happen as it is the exact same code executing on both devices...
This is built using PhoneGap/Cordova. The version of iOS is iOS 11 and the iOS device is an iPhone 8.
Here's the code:
var mathRandom = Math.random();
var data = {"file": {
"file": base64,
"filename": localStorage.username + mathRandom + ".jpg",
"filepath": "public://" + localStorage.username + mathRandom + ".jpg"
}
};
var result = $.ajax({
type: "POST",
data: data,
url: SITE_URL + "/" + ENDPOINT + '/file.json',
dataType: 'json',
async: false,
error: function (jqXHR, textStatus, errorThrown) {
moduleDebugger('account', errorThrown, "FILE SAVE ERROR");
return 'null';
},
success: function (data, textStatus, jqXHR) {
moduleDebugger('account', data, 'success');
}
});
(Yes, I know it is async, but this block of code absolutely MUST execute before anything after it - I am fine with the UX degradation)
I am using the same user, permissions are currently set so that ANYONE should be able to create files, even anonymously (for testing).
My CORS settings are these:
Internal path
Access-Control-Allow-Origin. Use <mirror> to echo back the Origin header.
Access-Control-Allow-Methods
Access-Control-Allow-Headers
Access-Control-Allow-Credentials
*|<mirror>|GET, PUT, POST, DELETE|Content-Type, Authorization, X-CSRF-Token|true
What would prevent a mobile user from saving a file, but not a user from localhost? Note, the server where the file will be saved is remote to both of these devices.
This is the error message:
Failed to load resource: the server responded with a status of 401
(Unauthorized : CSRF validation failed)
I am also getting the error:
Failed to load resource: Data URL Decoding Failed
But I am unsure if it is related to the above error - it comes a while after this error occurs. I have been unable to pinpoint what is causing it to occur.
EDIT: Even a static base64 string that I've tested repeatedly on localhost doesn't work.

Related

Cross domain request using jquery JSONP bult in

I have to implement a click button that downloads library (zip file) from non-local server. The task is simple: if you hit the URL you will have the zip file downloaded. I read in the internet that there is a restriction about cross-domain request, but there is also a workaround for that. So in the code below I applied one of the workarounds using jquery.
I tried ti simulate that click via this code:
$.ajax({
type: "GET",
url: "http://www.touchwand.com/wp-content/uploads/2018/04/Icons-and-backgrounds.zip",
dataType: 'jsonp',
success: function(data){
console.log(data);
},
error: function(xhr, status, err) {
console.log(xhr);
console.log(status);
console.log(err);
}
});
});
Gues what. Doesnt work. The file is not downloaded.
I get this error in the console:
Uncaught SyntaxError: Invalid or unexpected token
It is may be due to the returned response format is not JSON. But please tell me hot make it work?
* EDIT *
Changed the code to report errors.
The result is:
The request status is 200

JavaScript: Failed to load resource: the server responded with a status of 404 (Not Found)

I work on a JavaScript app that opens in the localhost address of https://localhost:63342/WalletClient/index.html_ijt=k4ock08pqsve8hb7b2b34ou3h5. It looks like this,
When I click the balance button, it should execute the following Ajax GET request and tries to open a new page balance.html,
$("#balance").click(function () {
address = $('#address option:selected').text().trim();
selectedCurrency = $('#selectCurrency option:selected').text().trim();
// make sure in the backend the currency name samll/capital doesnt matter
$.ajax({
url: "https://www.hostdomain.com" + "/rest/wallet/addressAndCurrency" + "/" + selectedCurrency + "/" + address,
type: "GET",
dataType: "json",
success: function (data) {
var id = data["id"];
window.open("/WalletClient/balance.html?walletId=" + id);
},
failure: function (errMsg) {
console.log(errMsg.toString())
}
});
});
However, in the console, I get the message of Failed to load resource: the server responded with a status of 404 (Not Found) and it seems that it tries to receive the GET request from the URL of :63342/WalletClient/https://www.hostdomain.com/rest/wallet/addressAndCurrency/Bitcoin/mnV3CR6435p1LKcbGa8GVwt9euWrf3wWEX
The Java app I worked is not deployed and hence, it won't be able to provide any responses. However, my concern is the GET request should try to receive the JSON from the URL of https://www.hostdomain.com/rest/wallet/addressAndCurrency/Bitcoin/mnV3CR6435p1LKcbGa8GVwt9euWrf3wWEX which is not trying to do.
What is the issue here?

Jquery AJAX always errors

I am using nginx web server and running a website on localhost. I want to be able to get my files through the server with jquery's AJAX function but it always throws an error. I've made a folder called TESTFOLDER inside my 'data' folder and it has a txt file called test.txt.
This is my javascript code
$.ajax({
url: "../data/TESTFOLDER/",
type: 'GET',
dataType: "txt",
headers: {
Accept : "text/html",
"Content-Type": "text/html"
},
success: function(data){
console.log('there was a success');
},
error: function (jqXHR, textStatus, errorThrown) {
console.log('there was an error');
}
});
This is my nginx configuration block for the folder
location /data/TESTFOLDER/ {
autoindex on;
try_files $uri $uri;
add_header Content-Type application/txt;
}
I always get this error:
NetworkError: 500 Internal Server Error
when it tries to reach the data/TESTFOLDER
I have of course tried it simpler than this, without the headers and all that. Nothing seems to work though. Please help if you can.
EDIT:
Yes, I can get to the file by typing out local host/data/TESTFOLDER/test.txt in my browser.
The ../ doesn't seem to be causing problems because in both cases, I get the error message 500 Internal Server Error - local host/data/TESTFOLDER/, i.e. not local host/../data/TESTFOLDER/
The server error log says: 2020#2644: rewrite or internal redirection cycle while internally redirecting to "/data/TESTFOLDER/", client: 127.0.0.1, server: localhost, request: "GET /data/TESTFOLDER/ HTTP/1.1", host: "localhost", referrer: "http:// localhost/index.html"
NOTE: The word local host is in two seperate words here because they won't allow me to post links.
EDIT2: I should note that while local host/data/TESTFOLDER/test.txt works fine in my browser, local host/data/TESTFOLDER/ throws the error 500. Should this be happening?
your url is malformed. if you want to use a relative path in an Ajax call, you don't need to use the ...
source: Relative URLs in AJAX requests
You can just use url: "/data/TESTFOLDER/". Your current url tries to access http://localhost:63542/../Data/TESTFOLDER/, which probably doesn't exist, but the server tries to locate it and throws an error.
You can catch different http-statuscodes with ajax.
Example:
$.ajax({
statusCode: {
500: function() {
// do something
}
}
});
You misuse try_files and get internal redirection loop.
Also, MIME type for text is text/plain.

XMLHttpRequest cannot load http://localhost:8089/jquery. Origin null is not allowed by Access-Control-Allow-Origin

I am trying to hit a webservice from jquery(ajax) using chrome. But when i try to invoke webservice i am getting below error and it is not even reaching the server
Error :XMLHttpRequest cannot load http://tomohamm-t420:8089/jquery. Origin null is not allowed by Access-Control-Allow-Origin.
Below is a sample ajax call which i am using:
//Build W/S-Request query as String object..
var id = '123';
var query = '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:sch="http://www.tibco.com/schemas/jQuerySample/jquery/Schema.xsd"';
query += '<soapenv:Header/';
query += '<soapenv:Body';
query += '<sch:EmpDetailsRequest';
query += '<sch:empID' + id + '</sch:empID';
query += '</sch:EmpDetailsRequest';
query += '</soapenv:Body';
query += '</soapenv:Envelope';
// set end point url..
var endpointUrl = 'http://tomohamm-t420:8089/jquery';
//ajax call to W/S..
$.ajax({
url : endpointUrl,
type : "POST",
beforeSend : function(xhr) {
xhr.setRequestHeader("SOAPAction", "/GetEmpByID");
},
data : query,
dataType : "xml",
contentType : "text/xml; charset=\"utf-8\"",
complete : function(xmldata,stat,response) {
console.log("W/S-Response: "+xmldata.responseText);
},
success : function(data) {
console.log('W/S Successful!');
},
error : function(textStatus, errorThrown) {
console.log('W/S Failed!');
console.log('Error Status :: ' +textStatus);
console.log('Error Message :: ' +errorThrown);
}
});
I found a way to avoid this issue. That is i have to open chrome using the below command:
cd C:\Program Files (x86)\Google\Chrome\Application
Chrome.exe --disable-web-security
But this cannot be done on every machine which tries to open my application.
So is there anyway to include this setting inside jquery application so that i can directly open chrome and run it?
I guess you are making ajax calls from a local file, right? If you want to do this some server side coding are needed.
Try this in you server side where you process the ajax request and send the response, adding the Access-Control-Allow-Origin header to the HTTP response and set the value to *. Here's a piece of Java code for your information.
response.setHeader("Access-Control-Allow-Origin", "*")
No. If you don't control the endpoint, your best bet is to proxy the request through your own server, and add the appropriate Access-Control-Allow-Origin headers.

IOS Webpage - Not Allowed by Access Control Allow Orgin

Im doing a simple ajax request like:`
$.ajax({
type: 'POST',
url: 'http://' + serverIP + '/saveJSON.php',
crossDomain: true,
data: 'helloooooooooo',
dataType: 'text',
success: function(responseData, textStatus, jqXHR) {
var value = responseData.someKey;
console.log(responseData);
console.log(textStatus);
},
error: function (responseData, textStatus, errorThrown) {
alert('POST failed.' + responseData);
console.log(responseData);
console.log(textStatus);
}
});`
And when running this in IOS Safari i get the error ...
"XML HttpRequest cannot load ...... Orgin ... is not allow by Access Control Allow Orgin
... Is to replace long URL's
I know I chrome I can by pass this by loading chrome with a -disable-web-security or other flags.
How can I get around this in iOS ? Security is not an issue as the devices will be locked down and only allow communication between certain IP address's.
Is there any other method of retrieving information from a server php script in JavaScript? That will be allowed?
Also any links to good websites for AJAX communication with PHP would be helpful.
Just to add, All my pages the client uses/sees are HTML (.html) and the server side is (.php)
Also when following THIS link for sorting this issue i added the header to my IIS 6 for my htmls are hosted and the ipad still doenst allow this.
Thanks guys
You can do this by adding Access-Control-Allow-Origin header.
In PHP it can be doing for example by adding new header in your PHP file:
header('Access-Control-Allow-Origin: *');

Categories

Resources