Daniel Paczuski Bak
Daniel Paczuski Bak

Reputation: 4080

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.
 */
});

Upvotes: 2

Views: 20305

Answers (3)

M.Hefny
M.Hefny

Reputation: 2745

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.");
    });

Upvotes: -2

matt
matt

Reputation: 1753

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

  });
});

Upvotes: 1

Omar Vazquez
Omar Vazquez

Reputation: 407

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

Upvotes: 9

Related Questions