Friday, 12 August 2016

Xây dựng một API Sever dùng nodejs

var express = require('express');
var http = require("http");
var https = require("https");
var app = express();

app.get('/api', function(req, res) {
    getRequest(host, path, method, headers, function(data) {
        res.senddata(data);
    })
});

app.listen(3000, function() {
    console.log('app listening on port 3000!');
});

function getRequest(host, path, method, headers, callback) {
    if (typeof callback == 'undefined')
        callback = function() {};

    var options = {
        host: host,
        path: path,
        method: method,   /* { 'GET' or 'POST' }*/
        headers: headers /* { 'Content-Type': 'application/json' }*/
    };

    var req = https.request(options, function(res) {
        res.setEncoding('utf8');
        res.on('data', function(data) {
            callback(data);
        });
        req.on('error', function(e) {
            callback(e);
        });

    });
    req.end();
}