JavaScript代码
- var http = require('http');
- var urllib = require('url');
- var port = 10011;
- var data = {'name': 'jifeng', 'company': 'taobao'};
- http.createServer(function(req, res){
- var params = urllib.parse(req.url, true);
- console.log(params);
- if (params.query && params.query.callback) {
- //console.log(params.query.callback);
- var str = params.query.callback + '(' + JSON.stringify(data) + ')';//jsonp
- res.end(str);
- } else {
- res.end(JSON.stringify(data));//普通的json
- }
- }).listen(port, function(){
- console.log('server is listening on port ' + port);
- })
自建Node路由Jsonp接口访问地址:http://liuxinxiu.com:3000/jsonp?Jsoncallback=2016&&name=liuxinxiu
JavaScript代码
- function jsonp(){
- this.exec=function(route,req,res){
- var data1={key:'value',hello:'world',name:'刘新修'};
- var data2={'name':'wangjiang','company':'taobao'};
- console.log(req+'---'+route)
- res.statusCode=200;
- //res.setHeader('content-type','application/json;charset=utf-8');
- //res.setHeader('Content-Type','text/html');
- //req.write(data);
- //req.end();
- var params=url.parse(req.url,true);
- console.log(params);
- if(params.query&¶ms.query.Jsoncallback){
- console.log(params.query.Jsoncallback);
- var str=params.query.Jsoncallback+'('+JSON.stringify(data1)+')';//jsonp
- res.end(str);
- }
- else{
- res.writeHead(200,{'Content-Type':'application/json'});
- res.end(JSON.stringify(data1)); //普通的json
- }
- }
- }
- module.exports=new jsonp();
自建Node路由Jsonp接口访问地址:http://liuxinxiu.com:3000/Jsoncallback?Jsoncallback=1&name=Jack
JavaScript代码
- function jsoncallback(){
- this.exec=function(route,req,res){
- /******** 处理请求判断用作JSONP ********/
- var params=url.parse(req.url,true);
- /********** 造数据要Obj不要String **********/
- var str2={dataList:[{name:"Jack",age:28,sex:1},{name:'Tony',age:30,sex:0}]};
- /********** 映射数据源无为undefined **********/
- var output=2016+'('+JSON.stringify(str2)+')';
- var result=params.query.Jsoncallback+'('+JSON.stringify(str2)+')';
- /************* 定义头部信息及编码规范 *******************/
- res.writeHead(200,{'content-Type':'application/json;charset=utf-8'});
- /************* 判断出来相应返回的结果 ********************/
- if(params.query&¶ms.query.Jsoncallback){
- res.write(result);
- res.end();
- }
- else{
- res.write(output);
- res.end();
- }
- }
- };
- module.exports=new jsoncallback();