How to process onmessage event data from websocket - javascript

I'm setting up a vert.x project in which I'm sending a snippet of JSON from my Java based server to a javascript client via websocket.
Vert.x server sending the JSON:
vertx.eventBus().send("mongodb-persistor", collectionsQuery, new Handler<Message<JsonObject>>() {
#Override
public void handle(Message<JsonObject> data) {
container.logger().info(data.body().encodePrettily());
ws.write(new Buffer(data.body().toString()));
}
});
The data being sent as outputted on the console:
{
"collections" : [ "AAPL", "AZN", "GOOG", "YHOO", "system.indexes" ],
"status" : "ok"
}
When i receive this on the client:
socket.onmessage = function(event) {
alert("Received data from websocket: " + event.data);
var x = JSON.parse(event.data);
};
I'm getting the error:
Uncaught SyntaxError: Unexpected token o (index):124socket.onmessage
I've read up and it appears as though that's because the JSON has already been parsed. So if I don't parse the JSON, how do i actually access my data? If i just output event.data as string, all I get is the type and size as opposed to the data logged on the console.
EDIT:
I also get the error "Failed to load resource: the server responded with status 404" off the following line /sometimes/, even though event.data is still populated with the correct message size.
alert("Received data from websocket: " + event.data);
Any help is appreciated and I hope this information is self contained enough!
Thanks :)

Turns out in vert.x I shouldn't be returning the JSON wrapped in a Buffer.
Instead I used the method writeTextFrame
vertx.eventBus().send("mongodb-persistor", collectionsQuery, new Handler<Message<JsonObject>>() {
#Override
public void handle(Message<JsonObject> data) {
container.logger().info(data.body().toString());
ws.writeTextFrame(data.body().encode());
}
});

Related

Why do I get "Uncaught SyntaxError" while parsing JSON string?

I am currently struggling with a JSON string that I receive from my server application.
This is the JavaScript snippet that receives the JSON string:
var connection = new WebSocket('ws://'+location.hostname+':81/', ['arduino']);
connection.onmessage = function (e) {
console.log('Received from server: ', e.data);
var response = JSON.parse(e.data);
if(response.action=="networks") {
console.log('SSID: ', response.ssid);
}
};
I get this response in my browser's console according to my console.log call above:
Received from server: {"action":"networks","ssid":"UPC6288862","rssi":-69,"enc":8}
Ending in the following error:
Uncaught SyntaxError: Unexpected token in JSON at position 60
at JSON.parse (<anonymous>)
at WebSocket.connection.onmessage (WebSocket.js:19)
connection.onmessage#WebSocket.js:19
When I manually put the string, to JSON.parse() like this:
var data = JSON.parse('{"action":"networks","ssid":"UPC Wi-Free","rssi":-42,"enc":255}');
the parsing works and I can access the fields by response.action for example.
But why I get the error? Is e.data not a proper string or do I need to add some quotes or similar to e.data before parsing?
UPDATE:
Here's a screenshot of Chrome's network tab while receiving the JSON string via the WebSocket.js:

Send file via Post using new SDK Firefox Addon

I'm searching to send a zip file to a server using the "Request" class from the new Firefox SDK for addons. This is my code:
var Request = require("sdk/request").Request;
var file = new FileUtils.File(pathToZipFile);
Request({
url: serverURL,
content: file,
onComplete: function (response) {
for (var headerName in response.headers) {
console.log(headerName + " : " + response.headers[headerName]);
}
console.log("Response " + response.text );
}
}).post();
But the error is:
[Exception... "Component returned failure code: 0x80520009 (NS_ERROR_FILE_INVALID_PATH) [nsILocalFile.target]" nsresult: "0x80520009 (NS_ERROR_FILE_INVALID_PATH)" location: "JS frame :: resource://gre/modules/commonjs/toolkit/loader.js -> resource://gre/modules/commonjs/sdk/querystring.js :: stringify/< :: line 70" data: no]
I have tried to do some checks and:
The server is on and receives normal GET and POST without files
The zip file is present and the path is right
Do you see any errors?
Thanks a lot
The only way to do it with the Request module is to base a base64 encoded string to the content key. If you don't use this, then you can send data such as a Blob or DOMFile (new File()) instance.
But as we see in the SDK code, the request module sends the data variable on request (if its not a HEAD or GET request).
https://github.com/mozilla/addon-sdk/blob/master/lib/sdk/request.js#L110
The data var is made by running stringify on anything passed to the content key:
https://github.com/mozilla/addon-sdk/blob/master/lib/sdk/request.js#L76
Stringify makes it a string:
https://github.com/mozilla/addon-sdk/blob/f5fab7b242121dccfa4e55ac80489899bb9f2a41/lib/sdk/querystring.js#L30
So you have to send base64 encoded string. Or a binary string. Which sucks.
You can use the sdk/io module to read the file as an ArrayBuffer and then turn that ArrayBuffer into a base64 string or binary string.
This shows how to get a binary string: https://stackoverflow.com/a/16365505/1828637

Trying to return json data from vimeo api in meteor

I am attempting to return some json data from the vimeo API in meteor and having some trouble with callbacks and server vs client stuff this is my following code, but it is not working because it can see the http request that's in a variable on the server side in client but if I put it in the client I get a blocking error
if (Meteor.isServer) {
var auth_url='http://vimeo.com/api/v2/video/92861889.json';
}
//invoke the server method
if (Meteor.isClient) {
result = Meteor.http.call("GET", auth_url);
var issue = JSON.parse(result.content);
console.log(issue);
}
Update: Current Error
Uncaught SyntaxError: Unexpected token < test.js?6011fceba7e0032b9fbc7fe1cec33965967603ed:24
(anonymous function) test.js?6011fceba7e0032b9fbc7fe1cec33965967603ed:24
(anonymous function) httpcall_client.js:63
(anonymous function) underscore.js:750
xhr.onreadystatechange
New Code
Ok so I retyped all the code, The issue was a invisible character from copying and pasting, from what I could tell. However Than I got a cross origin error, so I did some more research and found this is the proper way to do the callback. However I am getting a error "cannot read property "content" of undefined" Some More help would be greatly appreciated. I chose a different url for the json just for testing purposes.
if (Meteor.isServer) {
Meteor.startup(function () {
Meteor.methods({
'remoteGet' : function(url, options){
return HTTP.get(url,options);
}
});
});
}
if (Meteor.isClient) {
Meteor.call('remoteGet', 'http://www.kimonolabs.com/api/ahd8tq6q?apikey=6c55fc2ded8114a1c08b8a914851de84',{
},function(error,response){
var issue = JSON.parse(response.content);
console.log(issue);
});
}
On the client async operations cannot be written in a sync style. Callback is required:
if (Meteor.isClient) {
result = Meteor.http.call("GET", auth_url, function (err, result) {
var issue = JSON.parse(result.content);
console.log(issue);
});
}
Seems like Vimeo updated this Json data feed so it has to be :
https://vimeo.com/api/oembed.json?url=https://vimeo.com/{VIMEOID}

Backbone model.save calls error function on status code 200

this.model.save(newModel, {error: function (e){
alert("Error trying to save contact: " + e);
console.log(e);
}});
Above is the code that is running on the client side. the server code is
model.update_contact(contact, function(err){
if(err){
res.statusCode = 500;
return res.json({"Database error" : err});
}
return res.end();
});
inspecting the network traffic i see that the server responds with status code 200 but the web page shows the alert message "Error trying to save contact: [Object object]"
p.s the db query is successful
Backbone expects to get the model's JSON back in response to PUT or POST requests IIRC.
Instead of returning res.end() try this:
return res.json(contact);
Dumb mistake, my server was not properly returning the object back. Once i added code to return the object everything ran fine.

Recommendation on response handling for the ajax-upload script

I have used the multiple-file upload script from valums.com/ajax-upload/
How I can handle the JSON-response?
The actually input parameter 'responseJSON' of the onComplete function is some __proto__: Object object. It hasn't the valid JSON format.
However, the server response has the valid JSON format content. Below you may see onComplete function and debugger screenshot link.
Debugger screenshot - http://bit.ly/sB5mK0
Uncaught ТуреЕrrоr: Cannot read property 'src' of null
onComplete : function(id, filename, responseJSON) {
console.log('File upload for file %s, id %s done with status %s',
filename, id, responseJSON);
var json = $.parseJSON(responseJSON);
avatarPreview.attr('src', json.src);
}
You may see the request and response content on the next link:
http://pastebin.com/aWcTaUAJ
Thank you very much for your time!

Categories