how to make api server and call an api from node.js

making server for api interface

var sys = require("sys"),
    http = require("http"),
    url = require("url");

http.createServer(function(request, responsehttp) {
	responsehttp.writeHead(200, {"Content-Type": "text/html"});
	console.log(request.url);
	var url_parts = url.parse(request.url, true);
	var query = url_parts.query;
	console.log(query);
	var msg={
		'success':true,
		'message':'your request is sent to sms server and you will get notified when request completed.'
	};
	responsehttp.write(JSON.stringify(msg));
	responsehttp.end();

}).listen(8080);

to call an api from node.js

var smsclient=http.createClient(config.port, config.host);
	var request=smsclient.request('get','/index.php?msg=hello world',config);
	request.end();
	request.on('response', function(response){
		var result = "";
		response.on('data', function(chunk){
			result += chunk;
		})
		response.on('end', function(){
			console.log("result" + result);
		})
	});
var http = require('http');

http.createServer(function (req, res) {
    console.log('request received');
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('_testcb(\'{"message": "Hello world!"}\')');
}).listen(8124);
$(document).ready(function() {
    $.ajax({
        url: 'http://192.168.1.103:8124/',
        dataType: "jsonp",
        jsonpCallback: "_testcb",
        cache: false,
        timeout: 5000,
        success: function(data) {
            $("#test").append(data);
        },
        error: function(jqXHR, textStatus, errorThrown) {
            alert('error ' + textStatus + " " + errorThrown);
        }
    });
});

 

Ref :

http://stackoverflow.com/questions/5373987/how-to-use-jquery-ajax-calls-with-node-js

 

Advertisements

About rahul23134654

Hi, I am Rahul Meha , B.E. in (I.T.)
This entry was posted in Node.js. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s