responding with a json object in Node js - javascript

I want to return a Json object in 200 OK.
I am getting the data from my nosql.
I know the how to fill the structure. (that is in the json body the values to keep)
Here Name, Class and Address are fixed:
Name= entity[4]
Class= entityclass[4]
Address = entityaddrss[4]
...
enity..will be coming from nosql.
how can I construct and send a 200Ok with json body.
response.end({})
can you plesae let me what I should write in end.I have all the required data:
Name= entity[4]
Class= entityclass[4]
Address = entityaddrss[4]

Ok now that you added a few details in your first comment (you should edit the question and add these), I think I can answer what you are after.
var http = require('http')
var port = process.env.PORT || 1337;
var get_nosql_data = function(callback){
// do whatever it is here you need to get the data back
// and format it into a json object. pseudocode follows.
// error handling is also needed here, but not relevant to the answer
var db = require('db');
db.getData('some query', function(res){
var data = { name: res.entity[4], class: res.entityclass[4], address: res.entityaddrss[4] };
callback(data);
});
}
http.createServer(function(req, res) {
get_nosql_data(function(data){
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(data));
});
}).listen(port);
As long as you sub in the database values for the placeholder strings I have there, you should be up and running. This also should align with what azure already has set up for you.
Related, I would highly recommend checking out express - this will make your life a lot easier writing node web apps.

Related

How do I parse JSON from a URL for an AWS Lambda

I'm writing an AWS Lambda in node.js 6.10 for a school project with Amazon's Alexa software, and I don't have much experience with Javascript and none with JSON. My school has a transportation API for finding if it is up at: https://prtstatus.wvu.edu/api/[TENDIGITTIMESTAMP]/?format=json
If I go there with the stamp, I get "{"status":"7","message":"The PRT is closed.","timestamp":"1494028926","stations":[],"bussesDispatched":"0","duration":[]}"
What I am trying to get is the message and relay it to something else (I've got that part covered). What I don't know is how to break up the JSON response from the URL or write a request in the first place. Can someone help me figure out what to write to use the "message" string in my project?
So far I have:
'getPRTStatus': function() {
var date = Math.round(new Date().getTime()/1000);
//this is the spot where I need help filling in
//var object = JSON.parse('http://prtstatus.wvu.edu/api/'+date+'/?format=json');
this.attributes.speechOutput = this.t(object.message);
this.attributes.repromptSpeech = this.t(object.message);
this.emit(':ask', this.attributes.speechOutput, this.attributes.repromptSpeech);
},
Thanks for your help!
Is it possible for you to post the JSON response here from the URL because that would help a lot to narrow down the issue.
Update
You need to make an http get request to the API endpoint. You won't get a JSON response with,
var url = "http://prtstatus.wvu.edu/api/"+date+"/?format=json"
You can use a package like https://www.npmjs.com/package/request Check out their documentation on how you can make it work.
Something like this,
var options = {
"method": "get",
"url": "http://prtstatus.wvu.edu/api/1501906657/?format=json",
}
request(options, function(err, response, body) {
if (err) {
console.log(err)
} else {
console.log(body);
}
Another Update
You can try something like,
var request = require('request'); //Import the NPM package
var object; //global variable to be used later on to store the response
Then in your function,
'getPRTStatus': function() {
var date = Math.round(new Date().getTime()/1000);
var options = {
'method' : 'get',
'url' : 'http://prtstatus.wvu.edu/api/' + date + '/?format=json'
};
request(options, function(err, response, body){
if(err) {
console.log(err);
}
else {
object = JSON.parse(body); //You got the response parsed & stored in the global variable named object
}
});
this.attributes.speechOutput = this.t(object.message);
this.attributes.repromptSpeech = this.t(object.message);
this.emit(':ask', this.attributes.speechOutput,
this.attributes.repromptSpeech);
}
Just updated my answer according to your question. Hope that helps. For any future API related issues, you should try Postman in chrome. I'll post a link on how to get started with that. You will also get the direct code of your API call in postman.
Link to postman app: https://chrome.google.com/webstore/detail/postman/fhbjgbiflinjbdggehcddcbncdddomop?utm_source=gmail

reading request object in node.js from localhost

I'm new to node.js and I'm trying out a few easy examples using localhost:XXXX.
I want to read my request object from node. I have a book and in the book they use cURL(some program) to comunicate with node instead of the browser. Is it possible to write something in the browser adress field and send it to localhost and have a request object sent to node that looks exactly like if I had a typed in a url to a server somewhere? OIf so, how do I write? Do I have to use cURL or something like it if i use localhost?
I'm very new to node and javascript so I dont't know if I'm using the right words. I have tried to search but I dont't think I know the right terms to search for.
This is my server code:
var port = 3000;
http.createServer(function (req, res) {
var url = parse(req.url);
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello World\n' + url );
}).listen(port);
When i write http://localhost:3000/hello.com in the address field i was hoping i would get Hello world hello.com in the browser but i get hello world [object object]
Please help.
You can use your regular browser by testing it. In your URL address enter URL address that you have in your cURL address. For instance:
localhost:3000/index.html
If you would like to have more sophisticated tool that gives you more information about request/response you can use tool like Postman for that
In your code use:
res.end('Hello World\n' + url.parse(req.url, true));
url is an object, you need to specify property or method that you are calling on it.
Here is an example on how to parse URL. Easy URL Parsing With Isomorphic JavaScript:
Above answer given by #Vlad Beden looks good but you may want to play with following code
var http = require("http");
var port = 3000;
http.createServer(function (req, res) {
console.log('Requested method: ', req.method);
var params = parseUrl(req.url);
res.writeHead(200, { 'Content-Type': 'text/plain' });
var data = 'Hello World'
for(var i=0; i<params.length; i++)
data += '\n'+params[i]
res.end(data);
}).listen(port);
var parseUrl = function(url) {
var params = [];
if(url && url != '' && url != '/') {
url = url.replace(/^\/|\/$/g, '');
params = url.split('/');
}
return params;
}
You may try http://localhost:3000/hello.com or http://localhost:3000/hello.com/google.com/more.com/etc . I would like to recommend you print request object console.log(req) and have a look to understand url, method, headers, etc.

node.js + bulk json as response

I developed an REST API using node.js + express + elastic-search. In that i receive a request and send JSON as response. Everything is working fine.
In a particular situation(say /xxx/yyy/zzz?param1) the response is not sent to the front end. My application simply stays ideal doing nothing. My guess is that for this particular route the JSON response is very bulk i think so.
My code is:
app.get('/xxx/yyy/zzz', function(req, res){
return Ctr.getMaster(req, res);
});
DAO.prototype.master = function(callback) {
var query = {
from: 0,
size: 1000000,
index: 'masterdata',
query:"match_all"
}
client.search(query).then(function (resp) {
var obj = {};
obj.count = resp.hits.total;
obj.master = resp.hits.hits;
callback(null, obj);
}, function(error){
console.log(error);
});
};
How can i sort it out. I want to know whether the JSON is the problem? Or something else?/ How can i crack it. Please share your ideas.
Press F12 on browser and verify that is request received or not and how much size is there. Moreover, print console log on your backend API for json size.
Take look this one too 8937516

Node JS app only display the first JSON object. Why?

I am trying to write a json object in my node application, integrating the Twilio API. When console logging the object all objects are returned properly but when I write it to the document only the first object is written. Why? How should I change the code to see the same written response as in my console log.
var express = require('express');
var app = express();
app.use(express.bodyParser());
app.get('/', function(req, res) {
var accountSid = 'xxx';
var authToken = 'xxx';
var client = require('twilio')(accountSid, authToken);
client.messages.list({
from: "xxx",
to: "xxx"
}, function(err, data) {
data.messages.forEach(function(message) {
console.log(message.body); // THIS WILL DISPLAY ALL OBJECTS
res.json(message.body); // THIS WILL ONLY DISPLAY THE FIRST OBJECT
});
});
});
app.listen(1337);
I am new to Node JS and think this is easy to solve, but I still can’t find the solution.
res.json(...); sends back the response. You are doing that in the first iteration over the array, hence the client only gets the first message.
If you want to extract body from all messages and send all of them back, then do that. Create an array with the data you want and send it back. Example:
res.json(data.messages.map(function(message) {
return message.body;
}));
You can only call res.json once per request. You're calling it multiple times in a loop. The first time you call it, the browser receives the response, and you'll get a headers already sent exceptions (or something like that) for all other res.json calls.
res.json actually does a data conversion to JSON. I'd be willing to bet there is something it is not dealing with, or it's simply screwing it up. If the response from Twilio is already json, you probably don't need to do that. Try res.send, instead, which just returns whatever you got back.

Sending JSON object back to server through YUI IO utility?

I am running a web page that generates random data and displays it in a HTML table. From the table I run a loop to gather the basic information (all rows that exist and exclude headers of table). This data gets stored in a JSON object called jData.
I want to send this data back to the server and store in a sqlite table named data. The way I am trying to do this is therough the YUI IO utility.
I am trying to wade the API documentation, but I am having no luck. I have two buttons on the page. One to generate the data and on to store the data. The store code is as follows:
var savedata = function(){
var tabledata = Y.one("#generatedtable")._node;
var jData = [];
var i = 1;
var length = tabledata.rows.length
while (i<length){
var samplerow = {};
var r = tabledata.rows[i];
samplerow.timestamp = r.cells[0].innerHTML;
samplerow.volts = r.cells[1].innerHTML;
samplerow.amps = r.cells[2].innerHTML;
samplerow.kW = r.cells[3].innerHTML;
samplerow.kWh = r.cells[4].innerHTML;
jData.push(samplerow);
i++;
}
Y.io("./savedata", Y.System_Config.postjData(jData));
};
Using the chrome debugger tools I see the array being stored properly into jData. I need some basic help with Y.io and how to make posts. Any basic help is much appreciated. My server is run bu the Django Python web application framework.
You should read the IO User Guide. Making a POST request with JSON data in YUI is as simple as setting the HTTP method to POST, adding the data and setting the Content-Type to application/json. The only caveat is that you need to turn the JSON object into a string first using JSON.stringify().
Y.io('/savedata', {
method: 'POST',
data: Y.JSON.stringify(jData),
headers: {
'Content-Type': 'application/json'
},
on: {
success: function (id, response) {
// do something with the response from the server, for example
Y.one('#some-node').set('text', response.responseText);
}
}
});
You can read more about all the configuration options for IO in the "Configuration Object" section of the User Guide. There is an example there of a POST request with JSON data.

Categories