How to make multipart form api requests with requestjs and nodejs? - json

Trying to interact with the phaxio api using multipart form data. As per the request.js docs for making a post request I do
var request = require('request');
var options = {
uri: 'https://api.phaxio.com/v1/send',
headers: {'content-length':'0'}
};
var r = request.post(options);
var form = r.form();
form.append('api_key', '1234');
form.append('api_secret', '1234');
form.append('to', '1234');
r.on('response', function(chunk){
console.log(chunk);
});
The response body I get from the r.on method is here http://pastie.org/private/wshbn9esendccrkoreeiow I'm unsure how I can see the api response body from the server after submitting the form data. Something like
{
"success": true,
"message": "Fax Sent!"
}

The method request.post() returns a readable stream. Just read the response:
var res = '';
r.on('data', function(data) {
res += data;
});
r.on('end', function() {
console.log(res);
});
You can also pipe the response to another writable stream:
var fs = require('fs');
var writable = fs.createWriteStream('/file');
r.pipe(writable);

Related

how to render Rest api JSON data to the HTML page using Node.js without using jquery

I am trying to consume a RESTful API for JSON data and trying to display it on the HTML page.
Here is the code for parsing API into JSON data.
var https = require('https');
var schema;
var optionsget = {
host : 'host name', // here only the domain name
port : 443,
path : 'your url', // the rest of the url with parameters if needed
method : 'GET' // do GET
};
var reqGet = https.request(optionsget, function(res) {
console.log("statusCode: ", res.statusCode);
var chunks = [];
res.on('data', function(data) {
chunks.push(data);
}).on('end', function() {
var data = Buffer.concat(chunks);
schema = JSON.parse(data);
console.log(schema);
});
});
reqGet.end();
reqGet.on('error', function(e) {
console.error(e);
});
var express = require('express');
var app = express();
app.get('/getData', function (request, response) {
//console.log( data );
response.end(schema);
})
var server = app.listen(8081, function () {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
})
I am able to get the data in the JSON format but how do I display it in the HTML page? I am trying to do it using node js as I don't want to use jquery for that. Any help would be greatly appreciated. Thanks
your json can render through ejs
npm i ejs
var app = express();
app.set('view engine', 'ejs');
app.use(express.static(__dirname+'/public'));
app.get('/view/getData', function (request, response) {
//here view/getData is getData.ejs file in the view folder
response.render(__dirname+'/public/view/getData'',{schema: schema});
//schema is the object wich reference through the view in ejs template
});
your view file here getData.ejs
//store your getData in view/getData.ejs
<h> <%= schema[0]%> </h>//your json data here
basic ejs reference here
res.render brief explanation here

Pass a parameter from client-side to server side and get result

I knows it sounds basic but I can't seem to get it right. I'm trying to get a data from the API but it needs a parameter in order to obtain the data. How can I pass the parameter and get the result which is a JSON array
$(function() {
var proxy = 'http://192.168.1.126/lms-dev-noel/proxy.php';
var endpoint = 'account/';
var rt = 'GET';
var url = proxy+'?endpoint='+endpoint+'&rt='+rt;
var param = {
'lastsyncdate' : '2016-12-06'
};
$.get(url, function(param) {
console.log('Success');
});
});
ways to achieve this :
using jQuery.ajax() method :
var proxy = 'http://192.168.1.126/lms-dev-noel/proxy.php';
var endpoint = 'account/';
var url = proxy+'?endpoint='+endpoint+'&rt='+rt;
var method = 'GET';
var params = {
'lastsyncdate' : '2016-12-06'
};
$.ajax({
url: url,
type: method, //send it through get method
data: params,
success: function(response) {
//Do Something
},
error: function(xhr) {
//Do Something to handle error
}
});
using jQuery.get() method :
var proxy = 'http://192.168.1.126/lms-dev-noel/proxy.php';
var endpoint = 'account/';
var url = proxy+'?endpoint='+endpoint+'&rt='+rt;
var method = 'GET';
var params = {
'lastsyncdate' : '2016-12-06'
};
$.get(url, params, function(res) {
console.log(res);
});
I just pass parameters as name value pairs like so...
$.get(
"yoururl.php",
{ color: "red", size: "small" }, // your params go here as name / value pairs
function(response){
console.log(response);
}
);

Node.js HTTPS Request for Quandl API

I am using IBM Bluemix to make a web service for a school project.
My project needs to request JSON data from two APIs, for use in the project.
The first one is a http.request, which I executed just fine. For the second one, however, I need a https.request - and that is where the trouble comes from.
I don't know how to get a JSON through a https request. I've been trying to adapt the code for the http one, but my efforts have rendered useless.
How can I request a JSON via https?
Here is my .jsfile:
// Hello.
//
// This is JSHint, a tool that helps to detect errors and potential
// problems in your JavaScript code.
//
// To start, simply enter some JavaScript anywhere on this page. Your
// report will appear on the right side.
//
// Additionally, you can toggle specific options in the Configure
// menu.
function main() {
return 'Hello, World!';
}
main();/*eslint-env node*/
//------------------------------------------------------------------------------
// node.js starter application for Bluemix
//------------------------------------------------------------------------------
// HTTP request - duas alternativas
var http = require('http');
var request = require('request');
//HTTPS request
var https = require('https');
var https = require('https');
var fs = require('fs');
// cfenv provides access to your Cloud Foundry environment
// for more info, see: https://www.npmjs.com/package/cfenv
var cfenv = require('cfenv');
//chama o express, que abre o servidor
var express = require('express');
// create a new express server
var app = express();
// serve the files out of ./public as our main files
app.use(express.static(__dirname + '/public'));
// get the app environment from Cloud Foundry
var appEnv = cfenv.getAppEnv();
// start server on the specified port and binding host
app.listen(appEnv.port, '0.0.0.0', function() {
// print a message when the server starts listening
console.log("server starting on " + appEnv.url);
});
app.get('/home1', function (req,res) {
http.get('http://developers.agenciaideias.com.br/cotacoes/json', function (res2) {
var body = '';
res2.on('data', function (chunk) {
body += chunk;
});
res2.on('end', function () {
var json = JSON.parse(body);
var CotacaoDolar = json["dolar"]["cotacao"];
var VariacaoDolar = json["dolar"]["variacao"];
var CotacaoEuro = json["euro"]["cotacao"];
var VariacaoEuro = json["euro"]["variacao"];
var Atualizacao = json["atualizacao"];
obj=req.query;
DolarUsuario=obj['dolar'];
RealUsuario=Number(obj['dolar'])*CotacaoDolar;
EuroUsuario=obj['euro'];
RealUsuario2=Number(obj['euro'])*CotacaoEuro;
Oi=1*VariacaoDolar;
Oi2=1*VariacaoEuro;
if (VariacaoDolar<0) {
recomend= "Recomenda-se, portanto, comprar dólares.";
}
else if (VariacaoDolar=0){
recomend="";
}
else {
recomend="Recomenda-se, portanto, vender dólares.";
}
if (VariacaoEuro<0) {
recomend2= "Recomenda-se, portanto, comprar euros.";
}
else if (VariacaoEuro=0){
recomend2="";
}
else {
recomend2="Recomenda-se,portanto, vender euros.";
}
res.render('cotacao_response.jade', {
'CotacaoDolar':CotacaoDolar,
'VariacaoDolar':VariacaoDolar,
'Atualizacao':Atualizacao,
'RealUsuario':RealUsuario,
'DolarUsuario':DolarUsuario,
'CotacaoEuro':CotacaoEuro,
'VariacaoEuro':VariacaoEuro,
'RealUsuario2':RealUsuario2,
'recomend':recomend,
'recomend2':recomend2,
'Oi':Oi,
'Oi2':Oi2
});
app.get('/home2', function (req,res) {
https.get('https://www.quandl.com/api/v3/datasets/BCB/432.json?api_key=YOUR_API_KEY', function (res3) {
var body = '';
res3.on('data', function (chunk) {
body += chunk;
});
res3.on('end', function () {
var x=json.dataset.data[0][1];
console.log("My JSON is "+x); });
});
});
});
});
});
Your https.get should work as set up. There were a few other issues with your code that caused it to break, which I'm outlining below with explanations:
1. Potentially incorrect nesting of the /home2 route
Your declaration of the /home2 route was inside the declaration of your /home1 route. It is likely that you meant it to be outside. I've fixed this (and also fixed some indentation) in the code below.
2. json is undefined in the /home2 route's https.get callback
The variable json is not defined before use in the https.get callback function. You will need a line similar to the one you have in the http.get callback: var json = JSON.parse(body);.
Here's the fixed code for the routes
app.get('/home1', function (req,res) {
http.get('http://developers.agenciaideias.com.br/cotacoes/json', function (res2) {
var body = '';
res2.on('data', function (chunk) {
body += chunk;
});
res2.on('end', function () {
var json = JSON.parse(body);
var CotacaoDolar = json["dolar"]["cotacao"];
var VariacaoDolar = json["dolar"]["variacao"];
var CotacaoEuro = json["euro"]["cotacao"];
var VariacaoEuro = json["euro"]["variacao"];
var Atualizacao = json["atualizacao"];
obj=req.query;
DolarUsuario=obj['dolar'];
RealUsuario=Number(obj['dolar'])*CotacaoDolar;
EuroUsuario=obj['euro'];
RealUsuario2=Number(obj['euro'])*CotacaoEuro;
Oi=1*VariacaoDolar;
Oi2=1*VariacaoEuro;
if (VariacaoDolar<0) {
recomend= "Recomenda-se, portanto, comprar dólares.";
}
else if (VariacaoDolar=0){
recomend="";
}
else {
recomend="Recomenda-se, portanto, vender dólares.";
}
if (VariacaoEuro<0) {
recomend2= "Recomenda-se, portanto, comprar euros.";
}
else if (VariacaoEuro=0){
recomend2="";
}
else {
recomend2="Recomenda-se,portanto, vender euros.";
}
res.render('cotacao_response.jade', {
'CotacaoDolar':CotacaoDolar,
'VariacaoDolar':VariacaoDolar,
'Atualizacao':Atualizacao,
'RealUsuario':RealUsuario,
'DolarUsuario':DolarUsuario,
'CotacaoEuro':CotacaoEuro,
'VariacaoEuro':VariacaoEuro,
'RealUsuario2':RealUsuario2,
'recomend':recomend,
'recomend2':recomend2,
'Oi':Oi,
'Oi2':Oi2
});
});
});
});
app.get('/home2', function (req,res) {
https.get('https://www.quandl.com/api/v3/datasets/BCB/432.json?api_key=YOUR_API_KEY', function (res3) {
var body = '';
res3.on('data', function (chunk) {
body += chunk;
});
res3.on('end', function () {
var json = JSON.parse(body);
var x=json.dataset.data[0][1];
console.log("My JSON is "+x);
res.send('done https: JSON result: '+x);
});
});
});
Final note
You added your API key in the https URL. I would recommend changing the key, if sensitive information is involved.
The HTTPS server and client API is almost identical to the HTTP API.In fact, the client API is the same, and the HTTPS server only differs in that it needs a certificate file.
Starting the server
To start the HTTPS server, you need to read the private key and certificate. Note that readFileSync is used in this case, since blocking to read the certificates when the server starts is acceptable:
// HTTPS
var https = require('https');
// read in the private key and certificate
var pk = fs.readFileSync('./privatekey.pem');
var pc = fs.readFileSync('./certificate.pem');
var opts = { key: pk, cert: pc };
// create the secure server
var serv = https.createServer(opts, function(req, res) {
console.log(req);
res.end();
});
// listen on port 443
serv.listen(443, '0.0.0.0');
Note that on Linux, you may need to run the server with higher privileges to bind to port 443. Other than needing to read a private key and certificate, the HTTPS server works like the HTTP server.

nodejs puts post data into new json

When I sending post request by this code:
var data = '{data: 1111}'; // = JSON.stringify(message);
console.log('NotifySplitter: ' + data);
var options = cfg.splitterOptions;
options.headers['Content-Length'] = Buffer.byteLength(data)
var req = http.request(options, function(res) {
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log("body: " + chunk);
});
});
req.write(data);
req.end();
... and getting data by this code:
var express = require('express');
var app = express();
app.use(express.bodyParser());
app.post('/', function(request, response){
var query = request.body;
console.log(request.body);
response.end();
});
request.body contains:
{'{data: 1111}': ''}
instead expected {data: 1111}. Is it normal? How to get normal data without replacing external {} in origin data before post?
You have to set up an appropriate content-type. If you're sending json, add options.headers['Content-Type'] = 'application/json' to your request.
Also, {data: 1111} is not a JSON, it's JSON5. While it's better all around, it's not supported by default express.bodyParser(), so watch out for that.

Node Server receive XmlHttpRequest

I'm using the following code to send a session description (tiny JSON code - http://www.ietf.org/rfc/rfc2327.txt).
function sendMessage(message) {
var msgString = JSON.stringify(message);
console.log('C->S: ' + msgString);
path = '/message?r=67987409' + '&u=57188688';
var xhr = new XMLHttpRequest();
xhr.open('POST', path, true);
xhr.send(msgString);
}
I'm not sure how to go about retreiving the JSON on my Node.js server.
Here's a code that can handle POST request in node.js .
var http = require('http');
var server = http.createServer(function (request, response) {
if (request.method == 'POST') {
var body = '';
request.on('data', function (data) {
body += data;
});
request.on('end', function () {
var POST = JSON.parse(body);
// POST is the post data
});
}
});
server.listen(80);
Hope this can help you.