node.js, expressjs and jsonp example

Here’s a quick and simple example on how to make a jsonp call to a node.js + express server

node.js + express code:

var express = require('express');

var app = module.exports = express.createServer();

app.configure(function(){
  app.set('views', __dirname + '/views');
  app.set('view engine', 'jade');
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(app.router);
  app.use(express.static(__dirname + '/public'));
});

app.get('/logget', function(req, res){
  console.log('get to log');
  console.log(req.query.callback);
  console.log(req.param('somedata'))
  
  res.header('Content-Type', 'application/json');
  res.header('Charset', 'utf-8')  
  res.send(req.query.callback + '({"something": "rather", "more": "pork", "tua": "tara"});');  
});

app.listen(3000);
console.log("Express server listening on port %d in %s mode", app.address().port, app.settings.env);

Test html page:

<html>
	<head>
		<title>jsonp test</title>
		<script src="http://code.jquery.com/jquery-1.6.2.min.js"></script>		
		<script type="text/javascript">
            $(function(){				
                $('#jsonThingLink').click(function(e){
                    e.preventDefault();
                    console.log('jsonThingLink clicked');					
                    
                     $.ajax({
                        dataType: 'jsonp',
                        data: "somedata=blahblah",						
                        jsonp: 'callback',
                        url: 'http://localhost:3000/logget?callback=?',						
                        success: function(data) {
                            console.log('success');
                            console.log(data);
                            console.log(data.more);                
                        }
                    });
                });				
            });
        </script>
    </head>
    <body>
        <div id="jsonThing"><a href="#" id="jsonThingLink">test jsonp</a></div>    
    </body>
</html>

About these ads

3 thoughts on “node.js, expressjs and jsonp example

  1. Research is a tactical way to find a cheap bill consolidation
    loan bad credit or refinancing option. There are so
    many benefits from using car payment calculator will calculate the maximum amount of money
    involved.

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