JSON error in javascript when using websockets - javascript

I seem to be overlooking an error in my code that I just can't figure out. I have read multiple online sources showing what the error can be, but I can't find it in my code.
I am using WebSockets to communicate between my front and backend, when sending data in JSON format from my front to backend, it works perfectly, but not the other way around.
In my code snippets, I replaced my data with dummy values to make it easier to see the error.
Backend:
some_code.js
var msg = {"a": "a"};
Websocket.Send(msg);
websocket.js
Websocket.Send = (msg) =>
{
Websocket.Socket.clients.forEach(function each(client)
{
client.send(JSON.stringify(msg));
});
}
Frontend:
websocket.js
Socket.addEventListener("message", ({msg}) =>
{
console.log(JSON.parse(msg));
});
Error:
Any help will be appreciated, thanks!

Ok so changing the code of websocket.js to the following fixed it.
websocket.js
Socket.addEventListener("message", ({data}) =>
{
console.log(JSON.parse(data));
});
So it seems that the WebSocket library requires the variable name holding the received data to be named "data".

Related

Using json online

Heyo!
So, I'm trying to make something like https://aws.random.cat/meow however, when using my code with a discord bot, it isn't working.. It makes me wonder if you can host json things online directly by using the below code:
document.body.innerHTML = "<pre style=\"word-wrap: break-word; white-space: pre-wrap;\">{\"file\":\"https:\\/\\/"+domain+"\\/images\\/hug\\/"+item+"\"}</pre>";
Furthermore, my bot code is:
const { MessageEmbed } = require('discord.js');
const axios = require('axios');
const {get} = require("snekfetch");
const embed = new MessageEmbed()
.setColor("RANDOM")
.setTitle("thingie")
.setDescription("Loading...")
message.channel.send(embed).then(msg => {
get('https://example.com/kiss').then(response => {
setTimeout(function(){
embed.setDescription("")
embed.setImage(response.body.file)
msg.edit(embed)
}, 1500);
});
})
My website is working perfectly and is showing exactly as in https://aws.random.cat/meow However, it still doesn't work. Please lmk how or why this is happening.
P.S I didn't include the modules.export part in the bot code cuz, I thought it was extra.
P.P.S The following is my current output: This
Thanks!
If you want to provide data in a JSON format on your endpoint then just provide the JSON part, no need to put it in an HTML. If you put your JSON inside HTML like a string, then when you do get(<your url>) you'll get the entire HTML code with the embedded JSON, and so response.file doesn't work.
The reason why https://aws.random.cat/meow shows up as being embedded within HTML is because the browser detects that it is a JSON file and hence it does the embedding automatically. Here is the RAW response from that URL when you try to make the request using wget on the command line:
$ wget https://aws.random.cat/meow --no-check-certificate
$ cat meow
{"file":"https:\/\/purr.objects-us-east-1.dream.io\/i\/935392_10151612620866211_62628372_n.jpg"}
As you can see, there's no HTML around it. It's pure JSON.
To verify that this is indeed the case, log the response you get from your url:
get('https://example.com/kiss').then(response => {
console.log(response.body);
});
Unrelated: anyone else appreciate the cat meow coincidence here?

Parsing the text with React from server with Draft.js

I'm trying out Draft.js with my React application running with a GraphQL server. Currently I have a editor where I can type and add code blocks and submit it to the server. Here's the code for that:
const contentState = this.state.editorState.getCurrentContent()
const { content } = this.state.values
console.log('raw', convertToRaw(contentState))
let response;
try {
response = await this.props.mutate({
variables: {
content: JSON.stringify(contentState)
},
})
console.log(response)
response gives me
And that's no good. I rather have the convertToRaw(contentState) since that gives me:
The reason why I'm not doing convertToRaw(contentState) at mutate is because it gives me this error:
contentState.getBlockMap is not a function
So my questions are how can I use the convertToRaw function when submitting the text to the server and how can I later parse the text on the frontend so it wont look like this:
Thanks for reading my question. All help is appreciated!
Have a great day.

Sending data from AngularJs to NodeJs issue

I'm gonna start by showing you my code
Angular Code: app.js
$scope.submit = function(){
$scope.jsonData={
"status":"OK",
"data":{
"nbOperatorPresent": $scope.nbOperatorPresent,
"objectif1stHour": $scope.objectif1stHour,
"objectif2ndHour": $scope.objectif2ndHour,
"objectif3rdHour": $scope.objectif3rdHour,
"objectif4thHour": $scope.objectif4thHour,
"objectif5thHour": $scope.objectif5thHour,
"objectif6thHour": $scope.objectif6thHour,
"objectif7thHour": $scope.objectif7thHour,
"objectif8thHour": $scope.objectif8thHour
}
}
$http.post("http://localhost:5000/settings",
JSON.stringify($scope.jsonData)).success(function(data,status){
console.log('success')
})
}
NodeJs Code: index.js
app.post('/settings',urlencodedParser,function(req,res){
console.log(req.body)
})
As you can see, I have a button to submit the data inserted by the user and send it to the server.
My problem is, when I hit submit, there is nnothing in my browser console, I mean console.log('Success !') didn't work, that is to say that all the code inner the .success(function(data,status)) won't be executed so I can't notify the user that he has submitted Successfully, I don't know where the problem came from !!
BUT In the other console console.log(req.body) I found all the data that has been passed from Angular.
Can anyone explain this to me ? I've tried other solutions but always the same problem :(
To expand on the answer...
Please note if you are unfamiliar with node and express you may want to get in the habit of returning
res.send(success: true, data: res).end()
Its very typical on the angular or UI side to be able to parse as response.data object. Just a suggestion.
and change to this:
.success(function(res,status){
console.log(res.success, res.data)
})
This is a very common architecture especially when dealing with web services that you have not control over.
You're not returning anything from the node.js code. You need to add in a returning data like:
app.post('/settings',urlencodedParser,function(req,res) {
console.log(req.body)
res.send("Success")
})

NodeJS MSSQL Module Executing only Part of Stored Proc

So I have a node server, and I have it kicking off a stored proc for one particular internal tool. However, it seems it is dying part way through (seems to be once dynamic sql is used).
So it does a bunch of general sql commands, but seems to be dying when we hit:
set #cmd = N'Some stuff'
print #cmd
exec(#cmd)
my js server code is:
var connection2 = new sql.Connection(config2, function(err){
console.log("Connection 2 error - "+ err);
var request2 = connection2.request();
var spName = "nameOfSP";
console.log("---calling sp----");
request2.execute(spName,function(response){
console.log("SP response " + response);
})
});
I am getting this error:
SP response RequestError: Timeout: Request failed to complete in 15000ms
However, I am getting confirmation that the steps up until that dynamic sql is getting process almost instantaneously.
I've tried adding:
connectionTimeout: 30000
to my config, but it didn't seem to effect anything, which is making me feel like I'm not implementing that correctly. The documentation for this doesn't show much for this part.
Any help would be greatly appreciated.
Thanks!
I was specifying connectionTimeout, rather than requestTimeout.
This fixed it.

InDesign scripting of the Socket object yields cryptic error message

I'm working on a broadcast e-mail template that would pull the latest three articles off our blog from an RSS feed and insert the relevant sections into the document.
I looked at the documentation, and based on the bit about the File object, some of my own debugging, and an InDesign forum post I've learned that it's not possible to use the File object to source an online XML file.
The alternative (without resorting to an external script, one of which didn't work for me anyways), it seems, is to use the Socket object. So I went back to the documentation and copied/pasted this code verbatim from there:
reply = "";
conn = new Socket;
// access Adobe’s home page
if (conn.open ("www.adobe.com:80")) {
// send a HTTP GET request
conn.write ("GET /index.html HTTP/1.0\n\n");
// and read the server’s reply
reply = conn.read(999999);
conn.close();
}
When I ran it, I received this descriptive error message:
A search for "89858 javascript error" yielded nothing useful.
So I'm stuck. Either Adobe's code sample has an error, or, more likely, there's something wrong on my end. If I had to guess, I'd guess that it's some kind of proxy problem, but I don't know for sure and don't know how to find out.
Can anyone help? The principles of the Socket object make sense to me, but if I can't get even the sample to work, I don't really have anywhere to go with this.
The error above occurs when you return certain objects (XML, Socket) from a function call, but the return values does not get assigned anywhere.
function test() {
var xml = new XML('<test />');
return xml;
}
test();
The above will cause an error. To get around it you have to assign the return value somewhere.
var result = test();
Try to put all collect all function calls result. I am not sure which one causes the error.
var reply = "";
var conn = new Socket;
// access Adobe’s home page
if (conn.open ("www.adobe.com:80")) {
// send a HTTP GET request
var result = conn.write ("GET /index.html HTTP/1.0\n\n");
// and read the server’s reply
reply = conn.read(999999);
var close = conn.close();
}

Categories