I am using Jira API's to get data on single tickets. I have successfully setup a http GET request to the server and can display the data to the console however I ideally need to get certain properties from the data which is in JSON format.
When I try to read the properties I just get undefined.
var req = http.request(options, function(res) {
console.log('STATUS: ' + res.statusCode);
console.log('HEADERS: ' + JSON.stringify(res.headers));
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log('BODY: ' + chunk); // This displays the JSON
console.log('endSTATUS: ' + chunk.id); // This shows up undefined
});
The data is in this format from jira API for reference.
The first console log in the res successfully displays all the data from the chunk.
The second one is:
endSTATUS: undefined
Try to get the body after the data stream finish. Like this:
var body = '';
response.on('data', function(d) {
body += d;
});
response.on('end', function() {
// Data reception is done, do whatever with it!
var parsed = JSON.parse(body);
console.log('endSTATUS: ' + parsed.id);
});
Make sure you are parsing the response data as JSON. I think you may want something like var data = JSON.parse(chunk);, and reference the chunk data as data.value.
res.on('data', function (chunk) {
var data = JSON.parse(chunk);
console.log('BODY: ' + data);
console.log('endSTATUS: ' + data.id);
});
Related
I am trying to send sensor data to artik cloud via node.js. (using web socket and serial port). But its sending null. Anyone knows the reason? I just copied the code from tutorial so there is no syntax error.
var webSocketUrl = "wss://api.artik.cloud/v1.1/websocket?ack=true";
var device_id = "####";
var device_token = "#####";
var isWebSocketReady = false;
var ws = null;
var serialport = require("serialport");
var portName = 'COM5';
var sp= new serialport.SerialPort(portName, {
baudRate: 9600,
parser: serialport.parsers.readline("\r\n")
});
var WebSocket = require('ws');
/**
* Gets the current time in millis
*/
function getTimeMillis(){
return parseInt(Date.now().toString());
}
/**
* Create a /websocket bi-directional connection
*/
function start() {
//Create the websocket connection
isWebSocketReady = false;
ws = new WebSocket(webSocketUrl);
ws.on('open', function() {
console.log("Websocket connection is open ....");
register();
});
ws.on('message', function(data, flags) {
console.log("Received message: " + data + '\n');
});
ws.on('close', function() {
console.log("Websocket connection is closed ....");
});
}
/**
* Sends a register message to the websocket and starts the message flooder
*/
function register(){
console.log("Registering device on the websocket connection");
try{
var registerMessage = '{"type":"register", "sdid":"'+device_id+'", "Authorization":"bearer '+device_token+'", "cid":"'+getTimeMillis()+'"}';
console.log('Sending register message ' + registerMessage + '\n');
ws.send(registerMessage, {mask: true});
isWebSocketReady = true;
}
catch (e) {
console.error('Failed to register messages. Error in registering message: ' + e.toString());
}
}
/**
* Send one message to ARTIK Cloud
*/
function sendData(temperature){
try{
// ts = ', "ts": '+getTimeMillis();
var data = {
"temp": temperature
};
var payload = '{"sdid":"'+device_id+'", "data": '+JSON.stringify(data)+', "cid":"'+getTimeMillis()+'"}';
console.log('Sending payload ' + payload);
ws.send(payload, {mask: true});
} catch (e) {
console.error('Error in sending a message: ' + e.toString());
}
}
/**
* All start here
*/
start(); // create websocket connection
sp.on("open", function () {
sp.on('data', function(data) {
if (!isWebSocketReady){
console.log("WebSocket is not ready. Skip sending data to ARTIK Cloud (data:" + data +")");
return;
}
console.log("Serial port received data:" + data);
//var parsedStrs = data.split(",");
var temperature = parseInt(data);
sendData(temperature);
});
});
If you reference our First IoT Sample:
https://developer.artik.cloud/documentation/tutorials/your-first-iot-device.html
The node.js sample sends the value from the temperature sensor. As a dependency it requires a connected Arduino, Raspberry Pi, and a DHT temperature sensor located at the right pin. If you are seeing null "before" sending the data to ARTIK Cloud, you are not getting any value from the sensor.
In particular, output and print to console the "temperature" value from the following function in case of any parsing errors:
function sendData(temperature) //...
Email us at developer#artik.cloud if you need additional information.
Thanks!
In this line:
var temperature = parseInt(data);
If you're getting empty or non numeric data (you can verify this in the previous line where you're logging the variable's content), then temperature will be NaN (not a number). Then, when you build the JSON payload for Artik Cloud, you'll end up with something like:
{
"sdid": "cbd3f844967d464da3c4f4989f80f86c",
"data": {
"temp":null
},
"cid":"1495817841624"
}
Because the JSON.stringify of:
{"temp":NaN}
would be translated to:
{"temp":null}
.controller("addContact",function($scope,$http){
$scope.add=function(){
var myContact={
"department":$scope.department,
"name":$scope.name,
"model":$scope.model,
"year":$scope.year,
"price":$scope.price
};
console.log(myContact);
$http.post("/addItem",myContact)
.then(function(response){
console.log(response);
});
public.post('/addItem',function(request,response){
console.log("incoming data=" +request.body);
fs.readFile(__dirname + "/public/items.json", 'utf-8', function(err, data) {
console.log('file data' + data);
var fileJsonData = data;
var newContact = request.body;
newContact.id = fileJsonData.items.length + 1;
console.log("newContact=" + JSON.stringify(newContact));
fileJsonData.items.push(newContact);
var stringFile = JSON.stringify(fileJsonData);
fs.writeFile(__dirname + "/items.json", stringFile);
response.send(stringFile);
});
});
Please check if any of your interceptors are causing this issue. Also check the status of the response to check if it makes sense.
This post might help you Angular.js $http intercept "net::ERR_CONNECTION_REFUSED"
Take some time to read the document for $http.post as I think you are not using it the correct way
I am using Parse Cloud Code for retrieving JSON data from external API. JSON data are updated every 2 min.
To accomplish this, I am using Cloud Job to run my method every 2 minutes to keep data fresh. Also, I am storing whole JSON data to Parse.
When I run this code for the first time everything works well, but... when code runs for second, third or fourth time instead of updating objects it creates the new ones.
How to update objects instead of creating the new ones, when there are some data?
Code:
Parse.Cloud.define("getCars", function(request, response) {
var promise = new Parse.Promise();
var Cars = Parse.Object.extend('Cars');
var query = new Parse.Query(Cars);
query.find().then(function (results){
Parse.Cloud.httpRequest({
method: 'GET',
url: urlLink,
success: function(httpResponse) {
var stations = new Array();
var data = JSON.parse(decodeURIComponent(escape(httpResponse.text))); // utf-8 decode
for (var i = 0; i < data.length; i++) {
var Cars = Parse.Object.extend('Cars'),
car = new Cars(),
content = data[i];
car.set('number', content.number);
car.set('name', content.name);
car.set('address', content.address);
car.set('position', content.position);
car.set('status', content.status);
cars.push(station);
};
Parse.Object.saveAll(cars, {
success: function(objects) {
promise.resolve();
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
promise.reject(error.message);
}
});
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
promise.reject(error.message);
}
});
});
return promise;
});
SOLUTION
I have finally found the solution. Maybe this will be useful for other people who are facing the same problem.
I added a simple if statement which checks query result. If query does not return data, new object is created, otherwise: old object is filled with new information and saved into database.
station = (results == 0) ? new Stations() : results[i];
you are createting new object car = new Cars(), every time.instead find with objectId and in success response you will get ParseObject list(array).
update first parseObject from that list
I am using a client program called fire packets to fire some hexadecimal data on to a server program in which the server listening on a specified port. The server program works well and it receives the message from the client but need to convert the message into a json object in which results undefined when tried can any one please tell me how to do the conversion of the message into json object. Will attach the server program below,
var dgram = require('dgram');
var server = dgram.createSocket("udp4");
var fs = require('fs');
server.on("error", function(err) {
console.log("Error:" + err.stack);
server.close();
});
server.on("message", function(msg, rinfo) {
console.log("server got the message :" + msg + "from" + rinfo.address + "from the port" + rinfo.port);
fs.writeFile("packet.txt", msg.toString(), 'utf-8', function(err) {
//var jsonmess=JSON.parse(msg);
//console.log(jsonmess);
console.log("written on packet");
});
});
server.on("listening", function() {
var address = server.address();
console.log("Server listening on:" + address.address + "on the port:" + address.port);
});
server.bind(5432);
The message i send to through the client is
4500005100060000801116FB75610CFACF47D1F8501E5014003DD5C383051632426347010101020AC252F131AB52F131AB0776956F2CC65619000002CC0000000000000800005FFF970F07660001080100000032C8
When i stringify the JSON object the data has been shown as
[131,5,22,50,66,99,71,1,1,1,2,10,194,82,241,49,171,82,241,49,171,7,118,149,111,44,198,86,25,0,0,2,204,0,0,0,0,0,0,8,0,0,95,255,151,15,7,102,0,1,8,1,0,0,0,50,200]
How can i get the exact value that has been send through the client on a server json object
I want to parse a multidimensional array in Titanium.
It is something like this:-
{"nodes":
[{"node":
{
"title":"<a href=\"\/adf\/into-the-blue\">Into the Blue<\/a>",
"Teaser":"Into the Blue Teaser.",
"Knowledge":"<a href=fsdf">Americas<\/a>",
...
...
This is what I did. (It only gets the first row :( )
// url has the JSON URL.
var xhr = Titanium.Network.createHTTPClient();
xhr.onload = function() {
var response = xhr.responseText;
var resultObj = JSON.parse(response);
Ti.API.log("The Response is " + response);
Ti.API.log("THE RESULT " + resultObj);
updateBanners(resultObj);
updateTable(resultObj, catid, catregion, cattopic, listByDate);
};
xhr.open("GET", url);
xhr.send();
Many Thanks
Perhaps you are missing a piece from the parsing.
var resultObj = JSON.parse(response);
Mine usually looks like.
var resultObj = JSON.parse(response).NameOfMyRemoteFunctionResult;
I use WCF web service for my calls, so this is the type of response I get back.
This is how I was able to solve it.
//Correct Response. Gives the total number of returned Records.
resultObj.nodes.length
// and for a specific title of first row.
resultObj.nodes[0].node["title"]
alert("Total Records are :- "+ responseObjArr.nodes.length + " and the 1st Title is:- " + responseObjArr.nodes[0].node["title"]);