Saturday, 1 April 2017

Posting FROM Node's hosted router to a remote API (not TO Node's hosted API)

Wanting a Node router that POST Json to some remote API?

I put a lot of effort into this issue this morning so I wanted to share this by offering some comprehensive examples for your benefit.

In each example the router has a GET method that when called, POSTS back to the same router. I'm also showing, very clearly, how to send AND how to access the received data.

In Node.js, in a router, you might sometime what to post from the router to some remote api.

--- using npm install needle -save --- the file routes/nee.js ---

var express = require('express');
var router = express.Router();
var needle = require('needle');

router.get('/', function (req, resp) {
    var dat = { theGreatest: 'ChuckBerry' };
    var lookbackURL = 'http://' + req.headers.host + req.baseUrl;
    needle.post(lookbackURL, dat, { json: true });
    resp.redirect('/');
});


router.post('/', function (req, resp, next) {
    console.log('body.theGreatest', req.body.theGreatest);
    resp.sendStatus(200);
});


module.exports = router;

--- using npm install request -save --- the file routes/req.js ---

var express = require('express');
var router = express.Router();
var request = require('request');

router.get('/', function (req, resp) {
    var dat = { theGreatest: 'ChuckBerry' };
    var lookbackURL = 'http://' + req.headers.host + req.baseUrl;
    request.post(lookbackURL, { json: dat });
    resp.redirect('/');
});


router.post('/', function (req, resp, next) {
    console.log('body.theGreatest', req.body.theGreatest);
    resp.sendStatus(200);
});


module.exports = router;

--- using Node's very own http.request() -- the file routes/nodehttp.js ---

--- When you only want to POST some Json data make your life simpler by instead doing a PUT of the content-type=application/json -----

var express = require('express');
var router = express.Router();
var http = require('http');

router.get('/', function (req, resp) {

    var hst = req.headers.host.split(':');
    var dat = { theGreatest: 'ChuckBerry' };
    var bdy = JSON.stringify(dat);  // you have to take care of this for yourself
    var options = { host: hst[0], port: hst[1], path: req.baseUrl, method: 'PUT'  //PUT!
        , headers: { 'Content-Type': 'application/json' }
    };

    var r = http.request(options);
    r.write(bdy);
    r.end();
    resp.sendStatus(200);
});


router.put('/', function (req, resp) { // PUT. it's a PUT not a POST
    console.log('body[\'theGreatest\']', req.body['theGreatest']); // But here you DON'T have to parse it for yourself.
                 // ^ I'm happy for that even if I am feeling the loss of symmetry.
                 // ^^ At the same this is why your life is easier in a PUT instead of a POST.
    resp.sendStatus(200);
});


module.exports = router;

Enjoy & I hope these more comprehensive demonstrations help you too.



via user2367083

No comments:

Post a Comment