node.jsexpressjsonp

How to use jsonp with node.js express


i'm trying to make Samsung Smart TV app with node.js .

In my project, i want to make my app communicating with server pc.

According to Many Web sites, i can do this with "jsonp".

Here is a client side code that i found.

<html>
<head>
    <title>jsonp test</title>
    <script src="http://code.jquery.com/jquery-1.6.2.min.js"></script>      
    <script type="text/javascript">
        $(function(){               
            $('#select_link').click(function(e){
                e.preventDefault();
                console.log('select_link clicked');

                function test(data){
                    return {"message":"ok"};
                }

                 $.ajax({
                    dataType: 'jsonp',
                    data: "data=yeah",                      
                    jsonp: 'callback',
                    url: 'http://172.20.10.3:3000/endpoint?callback=?',                     
                    success: function(data) {
                        console.log('success');
                        console.log(JSON.stringify(data));
                    }
                });
            });             
        });
    </script>
</head>
<body>
    <div id="select_div"><a href="#" id="select_link">Test</a></div>    
</body>

And, here is a server side code that i found.

app.get('/endpoint', function(req, res){
var obj = {};
obj.title = 'title';
obj.data = 'data';

console.log('params: ' + JSON.stringify(req.params));
console.log('body: ' + JSON.stringify(req.body));
console.log('query: ' + JSON.stringify(req.query));

res.header('Content-type','application/json');
res.header('Charset','utf8');
res.send(req.query.callback + '('+ JSON.stringify(obj) + ');');
});

These codes are working on my pc(server pc), but when i open client page on others computer, it doesn't work.

Console just give me this log :

 X GET http://172.30.2.2:3000/endpoint?callback=jQuery11020685203080996871_1376482492523&data=yeah&_=1376482492524  

I want to use jsonp to handle cross-domain, but it doesn't work i think...

What can i do to fix this?

Please give me help!!


Solution

  • just use

    res.jsonp(obj)
    

    you can go ExpressJS JSONP for more info