nodejs puts post data into new json - 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.

Related

NodeJs - nested JSON POST input

I need to read nested JSON data in my Node.js server sent with a POST form.
For testing I'm using Postman with a POST request at 127.0.0.1:8080/extractByCenter, with Header Content-Type = application/json
and Body as "raw" JSON (application/json) with the following data:
{
"center": {
"lng":17.4152,
"lat":40.4479
},
"radius":20
}
My main .js file launched with node is very simple:
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var morgan = require('morgan');
var mongoose = require('mongoose');
//------------------------------------
//Configuration
//------------------------------------
var config = require('./config.js');
app.use(morgan('dev')); //remove dev at the end of development
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
//------------------------------------
//Routes
//------------------------------------
app.use('/', require('./routes/maprouter.js'));
//------------------------------------
//Server Start
//------------------------------------
mongoose.connect(config.DATABASE);
app.listen(config.SERVICE_PORT);
console.log('server start at port ' + config.SERVICE_PORT);
Where the maprouter.js just use a function of the MapManager.js:
var express = require('express');
var router = express.Router();
var MapManager = require("../managers/MapManager");
router.route('/extractByCenter').
post(function(req,res){
MapManager.extractByCenter(req.center,req.radius,function(err,data){
res.json({
success: true,
message: 200,
data: data
});
});
});
This function just takes the JSON data center and radius and it performs the query on the DB.
var _ = require('lodash');
var config = require('../config.js');
var GeoJSON = require('../models/GeoJSON.js');
var Manager = {
extractByCenter: function(center,radius,callback){
var query = {
'coordinates' : {
$near: {
$geometry: {
type: "Point" ,
coordinates: [ center.lng , center.lat ]
},
$maxDistance: radius,
$minDistance: 0
}
}
};
GeoJSON.find(query,'-__v -_id',callback);
}
}
module["exports"] = Manager;
The problem is the reading of the center data [ center.lng , center.lat ]:
I have a "TypeError: Cannot read property 'lng' of undefined"
Why center.lng (and surely also center.lat) doesn't work?
The bodyParser places things on req.body, not on req. So change your code to be req.body.center and req.body.radius and you should be good to go.
When you post to express, the body parser puts the request body into the body object. You're trying to access it off of req.center and req.radius instead of req.body.center, req.body.radius.
req.body.center, req.body.radius
var express = require('express');
var router = express.Router();
var MapManager = require("../managers/MapManager");
router.route('/extractByCenter').
post(function(req,res){
MapManager.extractByCenter(req.body.center,req.body.radius,function(err,data){
res.json({
success: true,
message: 200,
data: data
});
});
});
Ninja Edit:
Try doing a console.log of the req object so you can see all of the different things that it contains.
try
req.body
make sure that body parser has to be there

Download csv format using Angularjs

Node service: shown below are node service call where getting data from mysql query. And converting to json2csv format.
function getData(req,res){
var json2csv = require('json2csv');
var resultset = {};
resultset.data = [];
var nodeExcel=require('excel-export');
var dateFormat = require('dateformat');
var queryString = "select name ,class ,fname from details"
connection.query(queryString, function(err, result) {
if(err) {
console.log('error ',err);
resultset.success=false;
res.writeHead(200, {
'Content-Type': 'application/json'
});
var resultData =resultset;
res.write(JSON.stringify(resultData));
res.end();
} else {
if(result.length>0) {
for(var i=0;i<result.length;i++) {
resultset.data[i]={};
var arr=_(result[i]).toArray();
resultset.data[i].name=arr[0]!=null?arr[0]:null;
resultset.data[i].class=arr[1]!=null?arr[1]:null;
resultset.data[i].fname=arr[2]!=null?arr[2]:null;
}
resultset.success=true;
res.writeHead(200, {
'Content-Type': 'application/json'
});
var resultData =json2csv(resultset);
console.log("resultData",resultData);
res.write(JSON.stringify(resultData));
res.end();
}
else{
resultset.success = false;
res.writeHead(200, {
'Content-Type': 'application/json'
});
var resultData = resultset;
res.write(JSON.stringify(resultData));
res.end();
}
}
});
}
Controller:
getting the service response.
$scope.Details=function(data,fileName){
$http.get(Data.baseNodeService+'getData',headconfig).then(function(response,fileName){
$scope.det = response.data.data;
var element = angular.element('');
var anchor = angular.element('<a/>');
anchor.attr({
href: 'data:attachment/csv;charset=utf-8,' + encodeURI($scope.det),
target: '_blank',
download: 'filename.csv'
})[0].click();
});
}
On click Html Download:
<input type="button" class="bt-submit" ng-click="Details()" value="Download" />
But I am getting download output as [object Object].I want to get data from my service call and download in csv format.
You can download CSV in different ways, this below is a common way to download file
var a = document.createElement('a');
a.href = 'data:'+mimeType+';charset=utf-8;base64,' + response;
a.target = '_blank';
a.download = "name the file here";
document.body.appendChild(a);
a.click();
use the mimeType as your file type here for csv it would be attachment/csv but this won;t work on safari.
There is awseome library https://github.com/alferov/angular-file-saver You can use this.
You can call it like
function download(api, file, contentType) {
var d = $q.defer();
$http({
method: 'GET',
url: api,
responseType: 'arraybuffer',
headers: {
'Content-type': contentType
}
}).success(function(response) {
var data = new Blob([response], {
type: contentType+ ';charset=utf-8'
});
FileSaver.saveAs(data, file);
d.resolve(response);
}).error(function(response) {
d.reject(response);
});
return d.promise;
}
Also see my other answers on file download
how to export data into CSV and PDF files using angularjs
And
AngularJS - Receive and download CSV
Try this:-
/*this section for CSV*/
if(window.navigator.msSaveOrOpenBlob && window.Blob) {
var blob = new Blob([response.data.data], {type: "text/csv"});
navigator.msSaveOrOpenBlob(blob, new Date().getTime() + '.csv');
} else {
var anchor = angular.element('<a/>').css({display: 'none'});
angular.element(document.body).append(anchor); // Attach to document
anchor.attr({
href: 'data:attachment/csv;charset=utf-8,' + encodeURI(response.data.data),
target: '_blank',
download: new Date().getTime() + '.csv'
})[0].click();
anchor.remove();
}

How to print external API on my server? (Take user ip address and show it on website)

I have just started using nodejs and koajs, and I would like to take the ip address from here: https://api.ipify.org?format=json and paste it on my site or set it as a header. Right now I have the following:
var koa = require('koa');
var app = koa();
var http = require('https');
var a = http.get("https://api.ipify.org?format=json",function(res) {
var data = "";
res.on("data", function (chunk) {
data += chunk;
});
res.on('end', function() {
par = JSON.parse(data);
console.log(par.ip);
});
});
app.listen(8888);
app.use(function *(){
this.response.set("userIp",par.ip);
this.body = "ipadress: "; //this doesn't see par.ip;
});
I know that I am probably doing something very wrong here but yea I am currently stuck because I have no idea how to take par.ip and assign it to this.body and set.
Would anyone be able to tell me how to achieve this or an alternative to the problem? Thanks in advance.
Assuming the response from api.ipify.org doesn't change.
var koa = require('koa');
var app = koa();
var http = require('https');
var a = http.get("https://api.ipify.org?format=json",function(res) {
var data = "";
res.on("data", function (chunk) {
data += chunk;
});
res.on('end', function() {
par = JSON.parse(data);
console.log(par.ip);
app.use(function *(){
this.response.set("userIp",par.ip);
this.body = "ipadress: "; //this doesn't see par.ip;
});
app.listen(8888);
});
});
Otherwise if the response from api.ipify.org constantly changes, you might to do the http request on every incoming request.

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

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);

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.