How do I access HTTP POST data from meteor? - json

I have an Iron-router route with which I would like to receive lat/lng data through an HTTP POST request.
This is my attempt:
Router.map(function () {
this.route('serverFile', {
path: '/receive/',
where: 'server',
action: function () {
var filename = this.params.filename;
resp = {'lat' : this.params.lat,
'lon' : this.params.lon};
this.response.writeHead(200, {'Content-Type': 'application/json; charset=utf-8'});
this.response.end(JSON.stringify(resp));
}
});
});
But querying the server with:
curl --data "lat=12&lon=14" http://127.0.0.1:3000/receive
Returns {}.
Maybe params doesn't contain post data? I tried to inspect the object and the request but I can't find it.

The connect framework within iron-router uses the bodyParser middleware to parse the data that is sent in the body. The bodyParser makes that data available in the request.body object.
The following works for me:
Router.map(function () {
this.route('serverFile', {
path: '/receive/',
where: 'server',
action: function () {
var filename = this.params.filename;
resp = {'lat' : this.request.body.lat,
'lon' : this.request.body.lon};
this.response.writeHead(200, {'Content-Type':
'application/json; charset=utf-8'});
this.response.end(JSON.stringify(resp));
}
});
});
This gives me:
> curl --data "lat=12&lon=14" http://127.0.0.1:3000/receive
{"lat":"12","lon":"14"}
Also see here:
http://www.senchalabs.org/connect/bodyParser.html

Related

How can I add parameters in an HTML GET call using Electron.Net

I have the following function working from an Angular component (in an Electron application) using HttpClient:
var auth = "Bearer" + "abdedede";
let header = new HttpHeaders({ "Content-Type": 'application/json', "Authorization": auth});
const requestOptions = {headers: header};
const url = 'https://reqres.in/api/users?page=1';
this.http.get<any>(url, requestOptions).toPromise()
.then(response=> {
//...
alert(JSON.stringify(response));
});
}
Now, here is a call from the electron side which calls the same endpoint but without the Authorization and Content-Type in the header:
let buffers:any = [];
const { net } = require('electron')
const request = net.request({
method: 'GET',
url: 'https://reqres.in/api/users?page=1'})
request.on('response', (response) => {
console.log(`HEADERS: ${JSON.stringify(response.headers)}`)
response.on('data', (chunk) => {
buffers.push(chunk);
})
response.on('end', () => {
let responseBodyBuffer = Buffer.concat(buffers);
let responseBodyJSON = responseBodyBuffer.toString();
responseBodyJSON = responseBodyJSON;
})
})
request.end()
(This latter function is thanks to a poster replying here: In an Electron Application I am successfully making an HTTP GET request from an Angular component. How can I do the same thing from the Electron side?)
My question is, could anybody please advise\show me how to add in the Authorization and Content-Type Header info to this call so that it replicates what the Angular version does - i.e. by passing the requestOptions data in the GET call?
Thanks.
I have found it. I needed to add:
request.setHeader("content-type", "application/json"); request.setHeader("Authorization", auth);
before I call:
request.on('response', (response) => {

Change the content type in the request headers

I am supposed to send data from an app to the server and the post method from that app is made using content type as application/json but it is plain text. I cannot update the app to change this header now. The current app is working as the data reaches PHP directly and PHP doesn't parse the incoming data which is specified as json.
import express from 'express'
var http = require('http')
const redirectionRoutes = express.Router()
redirectionRoutes.use(function(req, res, next) {
req.rawBody = ''
req.headers['content-type'] = 'text/plain'
req.on('data', function(chunk) {
req.rawBody += chunk
})
req.on('end', function() {
next()
})
})
redirectionRoutes.post(/^\/update_services\/.*$/, function(request, response) {
var data = request.rawBody
var dataLength = data.length
var options = {
hostname: 'localhost',
port: 80,
path: request.path,
method: 'POST',
json: false,
headers: {
'Content-Type': 'text/plain',
'Content-Length': dataLength
}
}
var buffer = ''
var req = http.request(options, function(res) {
res.on('data', function(chunk) {
buffer += chunk
})
res.on('end', function() {
response.send(buffer)
})
})
req.write(data)
req.end()
})
But in nodejs(my application), as the content type is specified as json, the body parser is parsing the data and as it's not json, I am getting an error:
SyntaxError: Unexpected token # in JSON at position 0
at JSON.parse (<anonymous>)
at createStrictSyntaxError (../node_modules/body-parser/lib/types/json.js:157:10)
at parse (../node_modules/body-parser/lib/types/json.js:83:15)
at /Users/../node_modules/body-parser/lib/read.js:116:18
at invokeCallback (/Users/../node_modules/body-parser/node_modules/raw-body/index.js:224:16)
at done (/Users/../node_modules/body-parser/node_modules/raw-body/index.js:213:7)
at IncomingMessage.onEnd (/Users/../node_modules/body-parser/node_modules/raw-body/index.js:273:7)
at emitNone (events.js:105:13)
at IncomingMessage.emit (events.js:207:7)
at endReadableNT (_stream_readable.js:1047:12)
Is there a way in nodejs/body parser to not to parse this incoming json and let is get into the function as plain text.
It is solved!!
I am exporting this module at the end of the app code along with other pages routers. So, the body-parser being called in previous libraries are being called if I didn't use in this particular router.

nodeJS - make HTTPS request, sending JSON data

I would like to send an HTTPS POST from one nodeJS server to another. I have some JSON data I would like to send with this request (populated by a html form).
How can I do this? I am aware of https.request() but there does not seem to be an option to include JSON as a part of the query. From my research it seems possible with an HTTP request, but not an HTTPS request. How can I solve this?
const pug = require('pug');
var cloudinary = require('cloudinary');
var express = require('express');
var multer = require('multer');
var upload = multer({ dest: 'uploads/' });
var request = require('request');
var bodyParser = require('body-parser');
var options = {
hostname: 'ec2-54-202-139-197.us-west-2.compute.amazonaws.com',
port: 443,
path: '/',
method: 'GET'
};
var app = express();
var parser = bodyParser.raw();
app.use(parser);
app.set('view engine', 'pug');
app.get('/', upload.single('avatar'), function(req, res) {
return res.render('index.pug');
});
app.get('/makeRequest*', function(req, res) {
query = req['query'];
/*
Here, I would like to send the contents of the query variable as JSON to the server specified in options.
*/
});
You can send JSON data through a POST http request with the native https node module, as stated in the documentation
All options from http.request() are valid.
So, taking the http.request() example you can do the following:
var postData = querystring.stringify({
'msg' : 'Hello World!'
});
var options = {
hostname: 'www.google.com',
port: 80,
path: '/upload',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': Buffer.byteLength(postData)
}
};
var req = https.request(options, (res) => {
console.log(`STATUS: ${res.statusCode}`);
console.log(`HEADERS: ${JSON.stringify(res.headers)}`);
res.setEncoding('utf8');
res.on('data', (chunk) => {
console.log(`BODY: ${chunk}`);
});
res.on('end', () => {
console.log('No more data in response.');
});
});
req.on('error', (e) => {
console.log(`problem with request: ${e.message}`);
});
// write data to request body
req.write(postData);
req.end();
You should edit postData to your desired JSON object
I believe the below is what you want. Using the request library. See comments in the code for my recommendations.
...
var options = {
hostname: 'ec2-54-202-139-197.us-west-2.compute.amazonaws.com',
port: 443,
path: '/',
method: 'POST',
json: true
};
...
//making a post request and sending up your query is better then putting it in the query string
app.post('/makeRequest', function(req, res) {
var query = req.body['query'];
//NOTE, you cannot use a GET request to send JSON. You'll need to use a POST request.
//(you may need to make changes on your other servers)
options.body = { payload: query };
request(options, function(err, response, body) {
if (err) {
//Handle error
return;
}
if (response.statusCode == 200) {
console.log('contents received');
}
});
});
as matt mentioned you need to use request
to send JSON object not JSON.Stringify so that at the server you can receive it using:
app.post('/makeRequest', function(req, res) {
console.log (req.body.param1);
}
Use the following code:
var request = require("request");
request({
'url':"http://www.url.com",
method: "POST",
json: true,
body: {'param1':'any value'}
}, function (error, resp, body) {
console.log ("check response.");
});

Extracting a JSON Object from a URL

We are attempting to extract a JSON Object from a URL through http requesting. However, when we consistently getting the "undefined" when we try to return the text. Is there a problem in the way that we are implementing the http request?
function getUserData(email) {
var pathURL = "/" + email + "/data"
var options = {
host: 'localhost',
port: 3000,
path: pathURL,
method: 'GET',
headers: {
accept: 'application/json'
}
};
var x = http.request(options, function(res){
console.log("Connected");
res.on('data', function(data){
console.log(data);
});
});
}
Close the http.request() by using
x.end();
Here a reference to a similar question.
Sending http request in node.js
Try logging error as:
req.on('error', function(err){
console.log('problem with request:',err.message);
});
Meanwhile check the documentation of http library as well.
The response body are data but not returning to x.
var body = []
request.on('data', function(chunk) {
body.push(chunk)
}).on('end', function() {
body = Buffer.concat(body).toString()
// all is done, you can now use body here
})

Requesting a JSON using Request module (encoding issue) - Node.js

Im trying to request a Json file from a server different from mine but i cant set the right encoding.
I tried using HTTP module and failed.
Now im trying to do this using the 'Request' module.
The response i get is encoded to i dont know what. maybe utf 16 and is not readable at all.
Note: The json has some Hebrew chars in it.
I added the following to try and fix it but also failed:
headers: {'Content-Type': 'application/json; charset=utf-8'}
My code:
var http = require('http');
var request = require('request');
var express = require('express');
var app = express();
var url = 'http://www.oref.org.il/WarningMessages/alerts.json?v=1';
app.listen(process.env.PORT || 8080);
app.get('/', function(req,res){
res.send("Red color");
});
// get Alerts from web-service
app.get('/getAlerts', function(req,res){
request({
url: url,
json: true,
headers: {'Content-Type': 'application/json; charset=utf-8'}
}, function (error, response, body) {
if (!error && response.statusCode === 200) {
console.log(response.headers) // Print the json response
res.set({
'content-type': 'application/json'
}).send(body);
}
})
});
That API returns a JSON response encoded in UTF-16-LE, so you'll have to tell request to use that encoding instead.
However, since you're trying to query Pikud Haoref's alerts API, check out pikud-haoref-api on npm to do the heavy lifting for you:
https://www.npmjs.com/package/pikud-haoref-api