Node.js e le sue differenze con PHP: il caso delle richieste GET

Node.js e le sue differenze con PHP: il caso delle richieste GET

In Node.js le richieste GET non forniscono i dati in modo analogo a quanto avviene in PHP. Ci sono notevoli differenze.

In Node la difficoltà di una richiesta GET sta nell'intercettare il flusso di dati in arrivo utilizzando l'evento data e successivamente l'evento end a richiesta ultimata. In pratica si tratta di salvare i dati in una variabile man mano che questi arrivano.


var http = require('http');

var API = {
	base: 'api.host',
	getItems: function(id, callback) {
		var self = this;
		return http.get({
			host: self.base,
			path: '/api/items/' + id
		}, function(response) {
			var body = ''; // Variabile in cui salvare i dati in arrivo
        	response.on('data', function(d) {
            	body += d; // Dati in arrivo
        	});

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

module.exports = API;

Quindi possiamo usare il nostro modulo come segue:


var api = require('./app/models/api');

api.getItems(10, function(resp) {
	console.log(resp);
});

Torna su