Node.js: effettuare richieste ad API esterne in un'app Express

Node.js: effettuare richieste ad API esterne in un'app Express

Possiamo incapsulare le richieste alle API esterne in uno specifico wrapper nella nostra app Express.

Il wrapper effettua una chiamata alle API esterne e restituisce un oggetto JSON:


var http = require('http');

var API = {
	base: 'api.com',
	lookupProduct: function(productID, fn) {
		var self = this;
		return http.get({
			host: self.base,
			path: '/api/lookup/' + productID
		}, function(response) {
			var body = '';
        	response.on('data', function(d) {
            	body += d;
        	});

        	response.on('end', function() {
        		var parsedObj = JSON.parse(body);
        		fn(parsedObj);
        	});
		});
	}
};

module.exports = API;

Esempio d'uso nella nostra app:


var express = require('express');
var app = express();
var api = require('./models/api');
var bodyParser = require('body-parser');

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());


app.get('/products/:id', function(req, res, next) {
	api.lookupProduct(req.params.id, function(product) {
		res.json(product);
	});
});

Torna su