How to fetch a JSON with SparkAR networking module - json

I want to fetch data from an URL with SparkAR's networking module
and display it.
I tried the example found in the Spark AR documentation but it doesn't do much: https://developers.facebook.com/docs/ar-studio/reference/classes/networkingmodule/
Don't forget to add "jsonplaceholder.typicode.com"
to Spark AR's whitelisted domains first. :)
// Load in the required modules
const Diagnostics = require('Diagnostics');
const Networking = require('Networking');
//==============================================================================
// Create the request
//==============================================================================
// Store the URL we're sending the request to
const url = 'https://jsonplaceholder.typicode.com/posts';
// Create a request object
const request = {
// The HTTP Method of the request
// (https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods)
method: 'POST',
// The HTTP Headers of the request
// (https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers)
headers: {'Content-type': 'application/json; charset=UTF-8'},
// The data to send, in string format
body: JSON.stringify({title: 'Networking Module'})
};
//==============================================================================
// Send the request and log the results
//==============================================================================
// Send the request to the url
Networking.fetch(url, request).then(function(result) {
// Check the status of the result
// (https://developer.mozilla.org/en-US/docs/Web/HTTP/Status)
if ((result.status >= 200) && (result.status < 300)) {
// If the request was successful, chain the JSON forward
return result.json();
}
// If the request was not successful, throw an error
throw new Error('HTTP status code - ' + result.status);
}).then(function(json) {
// Log the JSON obtained by the successful request
Diagnostics.log('Successfully sent - ' + json.title);
}).catch(function(error) {
// Log any errors that may have happened with the request
Diagnostics.log('Error - ' + error.message);
});
All I get is : ">> Successfully sent - Networking Module"
Does anybody know how I could get the json content to be displayed in the console I want to store it and use it in a text object afterwards.

In my case a have a url that give me a random item in json format.
URL: https://gabby-airbus.glitch.me/random
Result: {"item":"Item 14"}
In the code, replace the line:
Diagnostics.log('Successfully sent - ' + json.title);
with this:
// show json data in console
Diagnostics.log(json.item);
// Asign json data to text object
itemText.text = json.item;
First line shows the json data in console.
Second line asign the json data to a text object in the scene, in this case the "itemText" text object.
Full code:
const Diagnostics = require('Diagnostics');
const Scene = require('Scene');
const Networking = require('Networking');
const URL = 'https://gabby-airbus.glitch.me/random';
var itemText = Scene.root.find('itemText');
Networking.fetch(URL).then(function(result){
if( (result.status >=200) && (result.status < 300)){ return result.json(); }
else { throw new Error('HTTP Status Code: ' + result.status); }
}).then(function(json){
// show json data in console
Diagnostics.log(json.item);
// Asign json data to text object
itemText.text = json.item;
}).catch(function(error){
itemText = 'Failed to start';
Diagnostics.log(result.status + error);
});

Related

CouchDb 2.1.1 Admin API Compaction PUT Request

I am working in NodeJS with CouchDB 2.1.1.
I'm using the http.request() method to set various config settings using the CouchDB API.
Here's their API reference, yes, I've read it:
Configuration API
Here's an example of a working request to set the logging level:
const http = require('http');
var configOptions = {
host: 'localhost',
path: '/_node/couchdb#localhost/_config/',
port:5984,
header: {
'Content-Type': 'application/json'
}
};
function setLogLevel(){
configOptions.path = configOptions.path+'log/level';
configOptions.method = 'PUT';
var responseString = '';
var req = http.request(configOptions, function(res){
res.on("data", function (data) {
responseString += data;
});
res.on("end", function () {
console.log("oldLogLevel: " + responseString);
});
});
var data = '\"critical\"';
req.write(data);
req.end();
}
setLogLevel();
I had to escape all the quotes and such, which was expected.
Now I'm trying to get CouchDb to accept a setting for compaction.
The problem is that I'm attempting to replicate this same request to a different setting but that setting doesn't have a simple structure, though it appears to be "just a String" as well.
The CouchDB API is yelling at me about invalid JSON formats and I've tried a boatload of escape sequences and attempts to parse the JSON in various ways to get it to behave the way I think it should.
I can use Chrome's Advanced Rest Client to send this payload, and it is successful:
Request Method: PUT
Request URL: http://localhost:5984/_node/couchdb#localhost/_config/compactions/_default
Request Body: "[{db_fragmentation, \"70%\"}, {view_fragmentation, \"60%\"}, {from, \"23:00\"}, {to, \"04:00\"}]"
This returns a "200 OK"
When I execute the following function in my node app, I get a response of:
{"error":"bad_request","reason":"invalid UTF-8 JSON"}
function setCompaction(){
configOptions.path = configOptions.path+'compactions/_default';
configOptions.method = 'PUT';
var responseString = '';
var req = http.request(configOptions, function(res){
res.on("data", function (data) {
responseString += data;
});
res.on("end", function () {
console.log("oldCompaction: " + responseString);
});
});
var data = "\"[{db_fragmentation, \"70%\"}, {view_fragmentation, \"60%\"}, {from, \"23:00\"}, {to, \"04:00\"}]\"";
req.write(data);
req.end();
}
Can someone point at what I'm missing here?
Thanks in advance.
You need to use node's JSON module to prepare the data for transport:
var data = '[{db_fragmentation, "70%"}, {view_fragmentation, "60%"}, {from, "23:00"}, {to, "04:00"}]';
// Show the formatted data for the requests' payload.
JSON.stringify(data);
> '"[{db_fragmentation, \\"70%\\"}, {view_fragmentation, \\"60%\\"}, {from, \\"23:
00\\"}, {to, \\"04:00\\"}]"'
// Format data for the payload.
req.write(JSON.stringify(data));

How to query third party JSON API from AWS Lambda function

I am working on a "Skill" for the new Amazon ECHO. The skill will allow a user to ask Alexa for information on the status and performance of an Enphase solar system. Alexa will respond with results extracted from the JSON based Enphase API. For example, the user could ask,
"Alexa. Ask Enphase how much solar energy I have produced in the last week."
ALEXA <"Your array has produced 152kWh in the last week.">
Problem is it has been years since I've programmed in JavaScript and this is my first time using AWS Lambda. I have not been very successful finding any information on how to embed a JSON query to a third party server within AWS Lambda function. Here is a relevant section of code in my Lambda function:
/**
* Gets power from Enphase API and prepares speach
*/
function GetPowerFromEnphase(intent, session, callback) {
var Power = 0;
var repromptText = null;
var sessionAttributes = {};
var shouldEndSession = false;
var speechOutput = "";
//////////////////////////////////////////////////////////////////////
// Need code here for sending JSON query to Enphase server to get power
// Request:
// https://api.enphaseenergy.com/api/v2/systems/67/summary
// key=5e01e16f7134519e70e02c80ef61b692&user_id=4d7a45774e6a41320a
// Response:
// HTTP/1.1 200 OK
// Content-Type: application/json; charset=utf-8
// Status: 200
// {"system_id":67,"modules":35,"size_w":6270,"current_power":271,
// "energy_today":30030,"energy_lifetime":59847036,
// "summary_date":"2015-03 04","source":"microinverters",
// "status":"normal","operational_at":1201362300,
// "last_report_at":1425517225}
//////////////////////////////////////////////////////////////////////
speechOutput = "Your array is producing " + Power + " kW, goodbye";
shouldEndSession = true;
// Setting repromptText to null signifies that we do not want to reprompt the user.
// If the user does not respond or says something that is not understood, the session
// will end.
callback(sessionAttributes,
buildSpeechletResponse(intent.name, speechOutput, repromptText,
shouldEndSession));
}
Some guidance would be much appreciated. Even if someone could point me in the right direction. Thanks!
Request is a very popular library for handling http requests in node.js. Here is an example of a POST using your data:
var request = require('request');
request({
url: 'https://api.enphaseenergy.com/api/v2/systems/67/summary',
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
key: '5e01e16f7134519e70e02c80ef61b692',
user_id: '4d7a45774e6a41320a'
})
}, function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log('BODY: ', body);
var jsonResponse = JSON.parse(body); // turn response into JSON
// do stuff with the response and pass it to the callback...
callback(sessionAttributes,
buildSpeechletResponse(intent.name, speechOutput, repromptText,
shouldEndSession));
}
});
I don't have an example of ECHO/Alexa but here is an example of Lambda calling out to get weather data to send it to Slack

how to get Json response from my node.js server and display it on web(ejs) page

i want to know how i can get a json response from my node.js server and display the response on my web page
below is the request and reponse in json code
var request = require("request"),
username = req.body.username,
password = req.body.password,
url = "https://api.ecoachsolutions.com/main.php?ecoachsignin=1&server=remote&user="+username+"&pass="+password;
console.log("url is "+url);
request.get(
{
url : url
},
function (error, response, body) {
// Do more stuff with 'body' here
if (!error && response.statusCode == 200) {
var json_body = JSON.parse(body);
console.log(json_body);
var msg = json_body.profile.user;//this is the message i want to show on my web page(msg)
console.log(msg); // get json response
}
}
);
You will first have to register express to use ejs:
app.engine('.html', require('ejs').__express);
then you can use res.render and pass your data to the view
res.render('index.html', {msg: json_body.profile.user});
After that you can access that via the EJS
<%= msg %>
If you need a working example, a good one can be found at:
https://github.com/strongloop/express/tree/master/examples/ejs

Node Express 4 get header in middleware missing

I have a middleware function using Node's Express4 to log each request & response for debugging. I use the res.json call in the request handler to send back JSON to the client for all but static files. So I do not want to log the response for static files, but only the JSON responses. I have the following code:
function logRequests(req, res, next) {
// do logging (will show user name before authentication)
logger.reqLog('IN '+req.method+' '+req.url, req);
var oldEnd = res.end,
oldWrite = res.write,
chunks = [];
res.write = function(chunk) {
chunks.push(chunk);
oldWrite.apply(res, arguments);
};
res.end = function(chunk, encoding) {
if(chunk) {
chunks.push(chunk);
}
oldEnd.apply(res, arguments);
// the content-type prints "undefined" in some cases
// even though the browser shows it returned as "application/json"
console.log('type='+res.get('content-type'));
if(res.get('content-type') === 'application/json') {
var body = Buffer.concat(chunks).toString('utf8');
logger.info(body, req);
}
logger.reqLog('OUT '+req.method+' '+req.path, req);
};
next(); // make sure we go to the next routes and don't stop here
}
So why do some requests show the correct content type in the middleware meaning they also print the response fine and others do not? All of them look good in the REST client when inspecting the returned headers.
EDIT: Some more info discovered tonight while trying to figure this out - if I append any character as a dummy request parameter, it logs the response type correctly:
http://localhost:8081/node/ionmed/api/logout?0 WORKS
where
http://localhost:8081/node/ionmed/api/logout DOES NOT
Also, I can always get a response type logging in the middleware function if I replace the .json() call with .end() so this:
res.json({ item: 'logout', success: true });
becomes:
res.set('content-type', 'application/json');
res.end({ item: 'logout', success: true });

nodejs - parsing chunked twitter json

The nodejs server 'gets' this JSON stream from Twitter and sends it to the client:
stream.twitter.com/1/statuses/filter.json?track=gadget
The data returned to the client is 'chunked' JSON and both JSON.parse(chunk) and eval('(' + chunk + ')') on the client side result in parsing errors.
Concatenating the chucked pieces and waiting for the 'end' event isn't a solution either
I noticed previous samples used something like this on the client side that apparently worked before:
socket.onmessage = function(chunk) {
data = eval("(" + chunk.data + ")");
alert(data.user.screen_name);
I'm using this on the client side and it results in a parsing error:
var socket = new io.Socket();
socket.on('message', function(chunk) {
var data = eval('(' + chunk + ')'); // parsing error
alert(data.screen_name):
I know that its successfully returning a JSON chunk with:
var socket = new io.Socket();
socket.on('message', function(chunk) {
alert(chunk): // shows a JSON chunk
Server:
response.on('data', function (chunk) {
client.each(function(e) {
e.send(chunk);
});
Did something change or what else em I doing wrong?
UPDATE: The 'end' event does not fire because its streaming?
http.get({
headers: { 'content-type': 'application/json' },
host: 'stream.twitter.com',
path: '/1/statuses/filter.json?track...
}, function(res) {
res.setEncoding('utf8');
res.on('data', function (chunk) {
client.each(function(e) {
e.send(chunk);
});
});
// does not fire
res.on('end', function () {
});
...
I'm looking into the difference with http 1.0 and http 1.1 as far as sending chunked data.
Look at the section titled Parsing Responses in Twitter's documentation.
Parsing JSON responses from the Streaming API is simple every object is returned on its own line, and ends with a carriage return. Newline characters (\n) may occur in object elements (the text element of a status object, for example), but carriage returns (\r) should not.
On the server side, keep accumulating chunks until you see the carriage return "\r". Once the carriage return is found, extract the string up to the carriage return, and that gives us one tweet.
var message = ""; // variable that collects chunks
var tweetSeparator = "\r";
res.on('data', function(chunk) {
message += chunk;
var tweetSeparatorIndex = message.indexOf(tweetSeparator);
var didFindTweet = tweetSeparatorIndex != -1;
if (didFindTweet) {
var tweet = message.slice(0, tweetSeparatorIndex);
clients.forEach(function(client) {
client.send(tweet);
});
message = message.slice(tweetSeparatorIndex + 1);
}
});
The client becomes simple. Simply parse the socket message as JSON in its entirety.
socket.on('message', function(data) {
var tweet = JSON.parse(data);
});
#Anurag I'cant add comments, however instead of
if (chunk.substr("-1") == "\r")
it should be:
if ( chunk.charCodeAt(chunk.length-2) == 13 )
The carriage return isn't the last character.
I would recommend piping the response into a JSON parser. You can use this: https://github.com/dominictarr/JSONStream