js and electron. I have a problem to push my local images file to my remote server. The server is using php. Here's my client side code :
var documentList = [];
var stmtDoc = db.prepare("SELECT * FROM `tb_dokumen_pasien`");
while(stmtDoc.step()) {
var rowDoc = stmtDoc.getAsObject();
var data = fs.createReadStream(__dirname + "/resources/" + rowDoc['id'] + "/" + rowDoc['doc_name']);
var document = {
"document_name" : rowDoc['doc_name'],
"data" : data
}
documentList.push(document);
}
And after that I create an ajax post request to my remote server :
$.ajax({
url: "http://url/web_api.php?action=test_upload",
type: 'POST',
data : { "document_list": documentList },
dataType: "json",
success: function(response) {
console.log(response);
}
});
When I test it, in my developer tools console I've got this message :
internal/streams/BufferList.js:15 Uncaught TypeError: Cannot read property 'length' of undefined
And the file is not sent to the server. Can anyone help me how can I solve this? Thanks
for a while I found the working solution for this problem is use base64 format to send it to the remote server :
var documentList = [];
var stmtDoc = db.prepare("SELECT * FROM `tb_dokumen_pasien`");
while(stmtDoc.step()) {
var rowDoc = stmtDoc.getAsObject();
var data = fs.createReadStream(__dirname + "/resources/" + rowDoc['id'] + "/" + rowDoc['doc_name']);
var base64 = Buffer.from(data).toString('base64');
var document = {
"document_name" : rowDoc['doc_name'],
"data" : base64
}
documentList.push(document);
}
And I still finding the best approach instead of using base64, Thanks
Related
On load of my page I execute this function
function getConnection() {
$.ajax({
type: "GET",
url: "../webservice/anonymous_PS.asmx/Get",
data: { "PSname": "LISTE_CONNEXTION" },
async : false ,
success: function (response) {
var data = response.getElementsByTagName("NewDataSet")[0]
for (let i = 0; i < data.children.length; i++) {
var c1Nb = $(data.children[i]).find('c1').text()
var c2Nb = $(data.children[i]).find('c2').text()
var c1 = document.getElementById("cs" + c1Nb)
var c2 = document.getElementById("cs" + c2Nb)
var line = $("#l_" + c1Nb + "_" + c2Nb)
}
}
})
}
But when I do that I have this error on Firefox :
XML Parsing Error: not well-formed
Location:
Line Number 1, Column 131:
and on chrome sometimes I have this error :
devtools was disconnected from the page
How can I resolve my issue ?
Try parsing your response, you can use $.parseXML(response) if you want to parse your response to xml or $.parseHTML(response) if you want to parse your response to html.
Once the parsing is done then your getElementsByTagName("NewDataSet")[0] will work and you will not get any error.
The final code will look something like:
var parsedResponse = $.parseXML(response);
var data = parsedResponse.getElementsByTagName("NewDataSet")[0];
I'm using this Javascript to send x, y values to Java from front-end (Javascript).
Sometimes this code pass the x any y values to Java and sometimes it's doesn't.After pressing the 'save' button, the function saveObjectMovingPath() will be called.
I don't know why it doesn't work sometimes! Can anyone help me to solve this issue?
<script type="text/javascript">
function saveObjectMovingPath() {
var building_Id = $("#building").val();
var floor_Id = $("#floor_level").val();
console.log('building_Id :' + building_Id + ', floor_Id : ' + floor_Id);
var json = {};
json["building_Id"] = building_Id;
json["floor_Id"] = floor_Id;
json["dataset"] = dataset;
$.ajax({
type: "post",
url: "savepath?pathConfig=" + unescape(JSON.stringify(json)),
success: function(data) {
alert("response data : " + data);
var response = JSON.parse(data);
}
});
}
</script>
This is sample data passing on URL:
"http://localhost:8080/Track/savepath?pathConfig={%22building_Id%22:%223%22,%22floor_Id%22:%2224%22,%22dataset%22:[{%22x%22:785.260498046875,%22y%22:624.4688720703125},{%22x%22:783.3544921875,%22y%22:624.4688720703125},{%22x%22:781.4485473632812,%22y%22:624.4688720703125},{%22x%22:779.5425415039062,%22y%22:624.4688720703125},{%22x%22:777.6365966796875,%22y%22:624.4688720703125},{%22x%22:775.7306518554688,%22y%22:624.4688720703125},{%22x%22:773.8246459960938,%22y%22:624.4688720703125},{%22x%22:770.9656982421875,%22y%22:624.4688720703125},{%22x%22:769.0596923828125,%22y%22:624.4688720703125},{%22x%22:767.1537475585938,%22y%22:624.4688720703125},{%22x%22:764.2947998046875,%22y%22:624.4688720703125},{%22x%22:763.341796875,%22y%22:624.4688720703125},{%22x%22:762.3887939453125,%22y%22:623.5159301757812},{%22x%22:760.4828491210938,%22y%22:623.5159301757812},{%22x%22:759.5298461914062,%22y%22:623.5159301757812},{%22x%22:757.6239013671875,%22y%22:623.5159301757812},{%22x%22:756.6708984375,%22y%22:623.5159301757812},{%22x%22:755.7178955078125,%22y%22:623.5159301757812},{%22x%22:754.7649536132812,%22y%22:623.5159301757812},{%22x%22:752.8589477539062,%22y%22:623.5159301757812},{%22x%22:751.9059448242188,%22y%22:623.5159301757812},{%22x%22:750.9530029296875,%22y%22:623.5159301757812},{%22x%22:749.0469970703125,%22y%22:623.5159301757812},{%22x%22:748.0940551757812,%22y%22:623.5159301757812},{%22x%22:747.1410522460938,%22y%22:624.4688720703125},{%22x%22:745.2350463867188,%22y%22:624.4688720703125},{%22x%22:744.2821044921875,%22y%22:625.421875},{%22x%22:743.3291015625,%22y%22:625.421875},{%22x%22:741.423095703125,%22y%22:625.421875},{%22x%22:740.4701538085938,%22y%22:626.3748779296875},{%22x%22:739.5171508789062,%22y%22:626.3748779296875},{%22x%22:738.5641479492188,%22y%22:626.3748779296875},{%22x%22:737.6112060546875,%22y%22:627.327880859375},{%22x%22:736.658203125,%22y%22:627.327880859375},{%22x%22:735.7052001953125,%22y%22:627.327880859375},{%22x%22:734.752197265625,%22y%22:627.327880859375},{%22x%22:733.7992553710938,%22y%22:628.2808227539062},{%22x%22:732.8462524414062,%22y%22:628.2808227539062}]}"
you try to send GET parameters on POST method
first you need to call the error function in your AJAX declaration and console.log it , if there is no error and the problem not resolved please check your java side (server side , maybe you try to save something need to parse ... )
second : make ajax statement look like this :
$.ajax({
type: "post",
data : {
building_Id : $("#building").val(),
floor_Id : $("#floor_level").val()
dataset: dataset;
}
url: "savepath?pathConfig=" + unescape(JSON.stringify(json)),....
....
instead of this :
var json = {};
json["building_Id"] = building_Id;
json["floor_Id"] = floor_Id;
json["dataset"] = dataset;
I'm trying to connect my google sheet to Bitfinex through the 'authenticated' section of the API so I can access my account information. Here is the API link.
I haven't been able to get the 'request' or 'crypto' libraries to work so I've been trying to use other available functions in google sheets, but am having trouble.
Following is the code snippet I'm using:
var completeURL = "https://api.bitfinex.com/v1/account_infos";
var nonce = Math.floor(new Date().getTime()/1000);
var body = {
'request' : completeURL,
'nonce' : nonce
};
var payload = JSON.stringify(body).toString('base64');
var signature = Utilities.computeHmacSignature(Utilities.MacAlgorithm.HMAC_SHA_384,
payload,
secret);
signature = signature.map(function(byte) {
return ('0' + (byte & 0xFF).toString(16)).slice(-2);
}).join('');
var params = {
headers: {
'X-BFX-APIKEY': key,
'X-BFX-PAYLOAD': payload,
'X-BFX-SIGNATURE': signature
},
}
Logger.log(completeURL);
Logger.log(params);
var response = UrlFetchApp.fetch(completeURL, params);
var json = JSON.parse(response.getContentText());
I get the following error from the API:
Request failed for https://api.bitfinex.com/v1/account_infos returned code 400. Truncated server response: {"message":"Invalid json."} (use muteHttpExceptions option to examine full response). (line 209, file "Code")
And the following are the values from the Logger.log calls:
[17-09-24 16:22:28:170 AEST] https://api.bitfinex.com/v1/account_infos
[17-09-24 16:22:28:171 AEST] {headers={X-BFX-PAYLOAD={"request":"https://api.bitfinex.com/v1/account_infos","nonce":1506234148}, X-BFX-SIGNATURE=06d88a85098aefbf2b56af53721506863978f9350b1b18386c23f446254789dbbfc1eeb520bdfc7761b30f98ea0c21a2, X-BFX-APIKEY=ak6UoPiwaLjwt2UqDzZzZGjpb9P2opvdPCAIqLy0eVq}}
I'm stuck and not sure what else to try?
Can anyone spot what I'm doing wrong?
How about this modification? Since I have no secret, I couldn't debug this sample. So I don't know whether this modified sample works. I'm sorry.
Modification points :
secret is not defined.
When POST method is used, it requires to include method: "post" to UrlFetchApp.fetch().
When it reads Javascript sample of the document, signature has to be modified.
When it reads Javascript sample of the document, body: JSON.stringify(body) is included in the request parameters.
There is an error message of {"message":"Invalid json."}.
The script which was reflected above modifications is as follows.
Modified script :
var secret = "#####"; // Please input this.
var completeURL = "https://api.bitfinex.com/v1/account_infos";
var nonce = Math.floor(new Date().getTime()/1000);
var body = {
'request' : completeURL, // I don't know whether this is the correct value.
'nonce' : nonce
};
var payload = Utilities.base64Encode(Utilities.newBlob(JSON.stringify(body)).getDataAsString());
var signature = Utilities.computeHmacSignature(Utilities.MacAlgorithm.HMAC_SHA_384, payload, secret);
signature = signature.map(function(byte) {
return ('0' + (byte & 0xFF).toString(16)).slice(-2);
}).join('');
var params = {
method: "post",
headers: {
'X-BFX-APIKEY': key,
'X-BFX-PAYLOAD': payload,
'X-BFX-SIGNATURE': signature
},
payload: JSON.stringify(body),
contentType: "application/json",
muteHttpExceptions: true
}
var response = UrlFetchApp.fetch(completeURL, params);
var json = JSON.parse(response.getContentText());
If this was not useful for you, I'm sorry.
I am not sure if I am understanding your code, but if I do, there is at least one oddity at first sight:
In computeHmacSignature(...), you are using the variable secret which has not been initialized or even declared anywhere.
That's how it works
var body = {
'request' : "/v1/balances",
'nonce' : nonce,
'options':{}
};
I am trying to send a POST request to my backend with some JSON data. The call from the frontend looks like this:
function register() {
var user = $("#form_reg_username").val();
var pass = $("#form_reg_password").val();
var referal = $("#form_reg_referal").val();
var postbody = {};
var url = "http://" + location.host + "/api/admin/register";
postbody.username = user;
postbody.password = pass;
postbody.referal = referal;
var jsonbody = JSON.stringify(postbody);
console.log(jsonbody);
$.ajax({
type: "POST",
url: url,
data: jsonbody,
dataType: "json",
success: registerHandler()
});
}
The generated log looks like this:
{"username":"jakob","password":"11111","referal":"urgotislove"}
Which is fine.
Here is the start of how I handle the request on the backend (I am using play 2.4)
public Result adminRegister() {
// Generate JSON from postbody
ObjectNode json = Json.newObject();
Logger.info("Body: " + request().body().asText());
JsonNode body = request().body().asJson();
String username = body.get("username").asText();
String password = body.get("password").asText();
String referal = body.get("referal").asText();
...
}
Looking at my application log the Info log looks like this:
[info] application - Body: null
I am then getting a Nullpointer Exception in first line of trying to get the json values.
So for some reason the POST body seems not to be received correctly.
Thanks for any help in advance.
Turns out the Postbody was transferred correctly but for some reason the .asText() as well as the .asJson() method, did not work correctly and returned null.
I fixed my issue with this little workaround:
Http.RequestBody requestBody = request().body();
Map<String, String[]> body = requestBody.asFormUrlEncoded();
String username = body.get("username")[0];
String password = body.get("password")[0];
String referal = body.get("referal")[0];
I'm currently working on incorporating an authorization feature for Twitter following the approach described here: https://dev.twitter.com/docs/auth/implementing-sign-twitter. I'm using Ajax to send my POST 'http' request, but I've been constantly running into a '401: Unauthorized' error. My code is below:
function getTweets() {
var time = generateTimestamp();
var nonce = generateNonce();
var signature = generateSignature(time, nonce);
var headers = {
"Authorization": 'OAuth oauth_callback="http%3A%2F%2Fwww.google.com%2F", oauth_consumer_key="eEeAAz9fakedtAOlIUhPgQ", oauth_nonce="bbc34b2ca6faabogus6dfc025907fa334", oauth_signature="' + signature + '", oauth_signature_method="HMAC-SHA1", oauth_timestamp="' + time + '", oauth_version="1.0"'
};
$.ajax({
type: "POST",
url: "https://api.twitter.com/oauth/request_token",
dataType: "text",
headers: headers,
success: function(data) {
alert("Success!");
console.log(data);
},
error: function(jq) {
alert("Request Failed.");
console.log(jq.statusText);
}
});
}
function generateTimestamp() {
var currentTime = new Date;
currentTime = Math.floor(currentTime.getTime() / 1000);
return currentTime;
}
function generateNonce() {
var code = "";
for (var i = 0; i < 20; i++) {
code += Math.floor(Math.random() * 9).toString();
}
return code;
}
function generateSignature(timestamp, nonce) {
var http_method = "POST";
var base_url = "https://api.twitter.com/oauth/request_token";
var consumer_key = "eEeAAz9hUKtdjunkeIUhPgQ";
var consumer_secret = "c7wHxnjubxVDcc5hYFqnotactuallymysecretWs2XazUFde0lPRBtBQ";
var signature_method = "HMAC-SHA1";
var token = "609493744-kNPzLKSI4Hg9NWQnopeFPb91eXFUutFm1nZ2hDk2";
var token_secret = "15WOJS9Ji1AXsKRkyAZrxKdsalted5Gj5ZyEAb9aVrJxI";
var version = "1.0";
var parameter_string = "oauth_callback=" + encodeURIComponent(base_url) + "&oauth_consumer_key=" + consumer_key + "&oauth_nonce=" + nonce + "&oauth_consumer_key=" + consumer_key + "&oauth_signature_method=" + signature_method + "&oauth_timestamp=" + timestamp +"&oauth_version=" + version;
var base_string = http_method + "&" + encodeURIComponent(base_url) + "&" + encodeURIComponent(parameter_string);
var signing_key = encodeURIComponent(consumer_secret) + "&";
var signature = encodeURIComponent(window.btoa(CryptoJS.HmacSHA1(base_string, signing_key)));
alert(signature);
return signature;
}
Feel free to post below if there's any other information that would make this error clearer. Thanks.
I created a node.js library to mess around with the Twitter OAuth dance and API. Code is here, tweeter.js
You're welcome to walk through the logic for creating the header and signature (starting at line 348 )
One thing I don't see in the code you've posted and which will make a huge difference is that the signature string must be generated to include the original header, then the header must be rebuilt with the generated string. It's a huge pain and it took me a while to figure it out.
Although the code I wrote is geared toward node.js, you should be able to reuse a lot of the logic to meet your needs.
EDIT
I found a site called hueniverse documented OAuth very well. In fact, there is a utility here to build your own headers for validating your logic (select the 'Create your own' radio button).
EDIT 2
To better explain including the oauth_signature value in the header, suppose you have all of the data up to this point:
var headerObj = {
oauth_consumer_key="123456789",
oauth_token="11111",
oauth_nonce="asdfghjkl%3B",
oauth_timestamp="1341852000",
oauth_signature_method="HMAC-SHA1",
oauth_version="1.0"
};
You create the HMAC-SHA1 signature and receive: "jBpoONisOt5kFYOrQ5fHCSZBGkI%3D"
You would then add that return value to headerObj, giving you:
headerObj = {
oauth_consumer_key="123456789",
oauth_token="11111",
oauth_nonce="asdfghjkl%3B",
oauth_timestamp="1341852000",
oauth_signature_method="HMAC-SHA1",
oauth_version="1.0",
oauth_signature="jBpoONisOt5kFYOrQ5fHCSZBGkI%3D"
};
And this modified version of headerObj is what you build your HTTP headers from.
GET / HTTP/1.1
Host: api.twitter.com:443
Authorization: OAuth realm="https://api.twitter.com/",
oauth_consumer_key="123456789",
oauth_token="11111",
oauth_nonce="asdfghjkl%3B",
oauth_timestamp="1341852000",
oauth_signature_method="HMAC-SHA1",
oauth_version="1.0",
oauth_signature="jBpoONisOt5kFYOrQ5fHCSZBGkI%3D"
NOTE: I didn't verify the host/realm/port, so these are probably wrong. Check the API for those.
The reason this is done is that on Twitter's side (this is an OAuth implementation detail), the oauth_signature value is removed and the rest of the header is hashed and its return value is compared to the value sent in oauth_signature. It's sort of like a wax seal on an envelope... if the hash of the rest of the header doesn't match the hash value you sent in oauth_signature, Twitter knows not to trust the sender or the contents.
EDIT 2.5
I'm moving this from the comment to the answer.
If you check out this line in tweeter.js, you'll see the logic.
var signature = self.oauthSignature(method, path, headerObj, query);
headerObj.oauth_signature = qs.escape(signature);
// concat the header object into a csv string
var header = 'OAuth realm="Twitter API",';
var oauthParts = [];
for (var h in headerObj) {
oauthParts.push(h + '="'+headerObj[h]+'"');
}
header+= oauthParts.join(',');
//...
return header;
This bit of code does as I've explained in EDIT 2, by converting a JSON object into key="value" strings stored in oauthParts[], then joins each element in that array into a single comma-separated string which begins with OAuth realm="Twitter API",