Fork me on GitHub

NodeJS中实现JSONP

var http = require('http');
var url = require('url');
var port = process.env.port || 1337;
var data ={"card":"2","user" : {"name": "Irving", "age": "24"},"numbers":{"Conway":[1,11,21,1211,111221,312211],"Fibonacci":[0,1,1,2,3,5,8,13,21,34]}};
http.createServer(function(req, rep){
  var params = url.parse(req.url, true);
  console.log(params);
  if (params.query && params.query.callback) {
     console.log(params.query.callback);
    //jsonp
    var str =  params.query.callback + '(' + JSON.stringify(data) + ')';
    rep.end(str);
  }else{
       rep.end(JSON.stringify(data));
  }     
}).listen(port, function(){
     console.log('server is listening on port ' + port);  
})

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Test NodeJS JSONP</title>
    <script src="http://code.jquery.com/jquery-latest.js"></script>
    <script type="text/javascript">
        $(function () {
            $("#test").click(function () {
                $.getJSON("http://localhost:1337/?callback=?",
                          function (data) {
                              alert(JSON.stringify(data));
                          });
            });
        });
    </script>
</head>
<body>
    <button id="test" type="button">Click me</button>
</body>
</html>

使用Express

$.ajax({  
     url: 'http://127.0.0.1:3000/',   //请求的是3000端口,应该属于跨域调用,因此dataType用jsonp  
     dataType: "jsonp",  
     //jsonpCallback: "_test",        //可以自定义‘处理’函数,默认是callback  
     cache: false,  
     jsonp:'callback',                //默认的传递处理函数是callback  
     timeout: 5000,  
     success: function(data) {  
         var data = $.parseJSON(data);  
         alert(data.message);  
     },  
     error: function(jqXHR, textStatus, errorThrown) {  
         alert('error ' + textStatus + " " + errorThrown);  
     }  
});


var express = require('express')       //引入express模块,当然也可以不用引入,而直接引入http模块  
  , app = express.createServer()  
  , url = require('url');  
app.get('/',function(req, res){  
  var queryObj = url.parse(req.url,true).query;  
  res.send(queryObj.callback+'(\'{"message": "test"}\')');  
  //res.send('_test(\'{"message": "test"}\')');     //对应jsonpCallback的函数  
  
});  
app.listen(3000);

Refer:

https://github.com/douglascrockford/JSON-js

http://cnodejs.org/topic/520d96da44e76d216a67eb8a

posted @ 2014-04-06 17:25  花儿笑弯了腰  阅读(479)  评论(0编辑  收藏  举报