I want to livestream telemetry data formatted in JSON from a websocket to a browser using javascript.
A websocket is created on a server X.X.X.X using native c and the websocketd wrapper on port 8080. A client (IP: Y.Y.Y.Y) shall connect to the very same server via https on port 80 (https://X.X.X.X:80) and shall receive javascript code which tells it to grab livestream data from the websocket (ws://X.X.X.X:8080) and refresh some values on the website with the values from this stream.
The data can exemplarily look like this:
{
"name of system": {
"RSSI": {
"rssi": "0",
"adc1": "0.00",
"adc2": "0.00",
"rxBatt": "0.00",
"swr": "0"
},
"ASS": {
"airspeed": "0.00"
}
}
}
{...}
and so on...
This frame shall be repeated e.g. in a 500ms interval and is sent with no whitespaces nor newline characters.
I tried parsing this already with JSON.parse() but my browser console returns following error: "Uncaught SyntaxError: Unexpected token *" or "Unexpected token {". Is this because of wrongly implemented JSON code, although I checked it several times?
My question is now: Is JSON.parse really capable of livestreaming? If not, are there libraries which are, or am I better off with a completely new solution?
Best regards
If the JSON parser is encountering an asterisk, as suggested by Unexpected token *, then your JSON is malformed, as that's not a valid character in JSON (outside of a string).
I'd recommend examining the message being received and visually check that it's valid JSON. Something like:
webSocket.onmessage = function(event) {
console.log(event.data);
}
Then, you can check your browser's developer console (usually Cmd-Shift-I on a Mac or F12 elsewhere) to see what you're actually receiving.
Related
Prevent server from crashing.
I am testing an API with Postman where I am expecting a number with or without decimal places.
But it happens that at the time of testing if I enter a sign like this in Postman: " ) " the server crashes automatically and it seems that it does not reach my validator.
Postman:
{
"concept": "Text",
"incomeAmount": 1)0000,
"expenseAmount": 89,
"description":"Text"
}
Failed response:
SyntaxError: Unexpected token ) in JSON at position 73
at JSON.parse ()
at parse (C:\project\node_modules\body-parser\lib\types\json.js:89:19)
at C:\project\node_modules\body-parser\lib\read.js:121:18
at invokeCallback (C:\project\node_modules\raw-body\index.js:224:16)
at done (C:\project\node_modules\raw-body\index.js:213:7)
at IncomingMessage.onEnd (C:\project\node_modules\raw-body\index.js:273:7)
at IncomingMessage.emit (node:events:402:35)
at IncomingMessage.emit (node:domain:475:12)
at endReadableNT (node:internal/streams/readable:1343:12)
at processTicksAndRejections (node:internal/process/task_queues:83:21)
I am using express validator like this:
router.post('/new-income',
[
check('incomeAmount', 'El Monto del Ingreso debe ser Númerico').isNumeric().not().isEmpty(),
check('expenseAmount', 'El Monto del Egreso debe ser Númerico').isNumeric().optional({ checkFalsy: true }),
],
validation,
newItem
);
And in the controller, I use Regex to verify that it is a positive number without symbols, but apparently neither the request nor the route arrives.
const regAmount = new RegExp('^[+]?([1-9][0-9]*(?:[\.][0-9]*)?|0*\.0*[1-9][0-9]*)(?:[eE][+-][0-9]+)?$');
if (!regAmount.test(incomeAmount)) {
return res.json ( {
'msg': 'Only positive numbers without signs are allowed'
} );
}
Thanks for your help!
With this much information I can only assume that you are using some kind of json middleware that parse the incoming data.
Unfortunately, the data you sent via postman is not in a valid json format. Ironically enough, only valid number are accepted as value without the need of quotation mark (excluding array and object).
A solution maybe to send the data as pure text to your api and then run in through your validation before converting it into a number.
You can verify the json format yourself here: https://jsonformatter.curiousconcept.com/
This is expected. You're sending illegal JSON so your JSON parsing middleware gets an exception. To catch/handle this error, you need to either install custom middleware that catches the error in the middleware or catch the error from the existing JSON parser in the Express error handler by installing your own Express error handler.
Also, if you're using the express.json() middleware, it has a verify callback option that you can pre-check the JSON if you want, but frankly, it's probably easier to just have an Express error handler and get the error there.
I am getting an error that says SyntaxError: Unexpected token a in JSON at position 0
and I cannot find any information on what "a" means. I know that the JSON is not undefined.
Can anyone help me understand what is causing this error?
Here is the code block that is causing the error:
let db_creds = await getDBCredentials();
console.log(db_creds)
const pool = new Pool(JSON.parse(db_creds['SecretString']));
console.log(pool)
Unexpected Token < in JSON at Position 0. From time to time when working with JSON data, you might stumble into errors regarding JSON formatting. For instance, if you try to parse a malformed JSON with the JSON. ... json() method on the fetch object, it can result in a JavaScript exception being thrown.
What Is JSON and How to Handle an “Unexpected Token” Error
Well for me it was because the port was already in use and it must be sending HTML, you can try killing the port by running the below command in cmd(admin mode)
taskkill /F /IM node.exe
I am trying to connect an Azure Function to a SQL-Database that I also created in Azure. Sounds pretty simple and Microsoft even has a pretty good POC tutorial for it. However, in my case the Azure Function is dropping "entryPoint" errors that I am not able to resolve.
I checked some other stackoverflow discussions (Can't connect Node.js server to Azure SQL Database) and googled the hell out of it. Unfortunately it seems like none of this is helping. I updated the "function.json" to set my entryPoint as shown below.
{
"bindings": [
{
"authLevel": "function",
"type": "httpTrigger",
"direction": "in",
"access": "listen",
"name": "req",
"methods": [
"get",
"post"
]
},
{
"type": "http",
"entryPoint": "index",
"direction": "out",
"name": "res"
}
]
}
My index.js code is a very trivial try to connect to the database and tell me about the success.
var Connection = require('tedious').Connection;
var config = {
userName: 'XXXX',
password: 'XXXX!',
server: 'XXXX.database.windows.net',
// If you are on Microsoft Azure, you need this:
options: {encrypt: true, database: 'XXXXX'}
};
var connection = new Connection(config);
connection.on('connect', function(err) {
// If no error, then good to proceed.
console.log("Connected");
});
Normally this should connect to the database and print a "Connected" to the console but somehow it shows this error:
[Error] Executed 'Functions.TediousTest' (Failed, Id=XXXXXXX)
node exited with code 1
[error] Worker was unable to load function TediousTest: 'Unable to determine function entry point. If multiple functions are exported, you must indicate the entry point, either by naming it 'run' or 'index', or by naming it explicitly via the 'entryPoint' metadata property.',[error] Worker XXXXXX uncaught exception: ReferenceError: executeStatement is not defined
Hopefully this is enough information to understand my problem. The database has no special firewall etc. at the moment. Besides it seems like the code snippet isn't even able to get in touch with the firewall. Thanks in advance.
I believe you haven't exported your function properly based on the error message - basically missed the module.exports line.
I guess your code looks something like this
...
async function TediousTest() {
...
}
If so, just add this line to the end
module.exports = TediousTest;
I have a JavaScript application which is running in Node.js environment and communicates to its clients ( also in JavaScript ) using a ZeroMQ. The messages come on the server in JSON format.
The application code throws it out
Node.js SyntaxError: Unexpected token in JSON at position 0
when it is parsed using JSON.parse(). I'm unable to figure out the issue. I've verified the JSON using http://jsonlint.com
Any help with JSON.parse() is welcome.
Edited:01/10/17, 15:33
Here are the client and server JavaScript code files. You'll need to create the .js files, can't post such a big code.
The JSON data file is also provided.
You'll need to launch the server.js and client.js and then the server console will print out the exception for unrecognized character.
https://www.4shared.com/folder/6VFJqrgU/javascript.html
Stackoverflow imposes link posting restrictions so had to post one link with all the files.
Just for info, I'm a C++ programmer, so don't bother about the code formatting or style of programming. I had to do it for a project need.
Edit 02/10/17, 11:50: Well it turns out that it is the JSON.parse() method which is unable to parse the json. But, I added a .trim() call to the args[1].toString() and the error has moved downstream. Unexpected token o in JSON at position 10. I don't understand what is wrong!!
Edit 04/10/17: Here is the minimal code.
var fs = require('fs');
try
{
var event = fs.readFileSync('demoReport.json', 'utf8');
console.log(event);
var eventObj = JSON.parse(event);
var reportName = event["ReportName"];
var reportData = event["ReportData"];
console.log(reportData);
}
catch(error)
{
console.log("JSON parsing failed: " + error);
}
This is the json:
{"EventName":"ReportGenEvent","TemplateFileNameLocation":"File location","ReportFormat":".pdf","ReportName":"TestReport","ReportLocation":"report location","Locale":"French","ReportData":{"dateTime":"2017-09-29T00:05:22.824Z","streamName":"","measurementTime":"2017-04-01T01:13:25.000Z","durationSeconds":0.0,"outOfBand":false,"notFinal":false,"newMeasurement":false,"savedFileName":"","measurementType":"Unknown","analysisElapsedSeconds":1.3462,"analysisElapsedCPUSecs":0.0624004,"geometryID":"GEOM","geometryDescription":"","measurementUUID":"6060c80f-007c-4992-88f8-55e2200d99b7","backgroundUUID":"","measurementWorkflowID":"Measurement","instrumentProperties":{"classCode":8,"description":"","manufacturer":"","model":"","properties":"locationName=Home latitude=25 longitude=20 elevation=30","serialNumber":"product/1","versionInformation":"=V1.0"}}}
Thanks.
I have a JSON that looks like so:
{
"response": {
"event": "Other",
"time_opened": "2014-09-09 10:09:07",
"time_updated": "2014-09-10 09:34:55",
"name": "blablablablablabla",
"current_status": "blablabla
blablablablablablablablablablablabla
blablablablablablablablabla
blablablablablablablablabla
"
}
}
I get "Uncaught SyntaxError: Unexpected token" on JSON.parse. After research I couldn't figure out how to wrangle it. Sorry if duplicate, but I'm a little lost here.
The problem was resolved with appropriate encoding server side.