使用NodeJs实现CORS 跨域资源共享,可传参origin通过限制,代码如下:

JavaScript代码
  1. var http=require('http');  
  2. var origin=require('./origin'); //调用白名单列表  
  3.   
  4. function CORS_Node(){  
  5.     this.exec=function(route,req,res){  
  6.     var _self=this;  
  7.   
  8.     /************** 获取客户端origin的域名 **************/  
  9.     origin.req=req;                //白名单设置置请求头  
  10.     origin.yes=origin.listV();     //是否在名单|true  
  11.     origin.name=origin.getName();  //客户端ORIGIN  
  12.   
  13.   
  14.     /******** 先纠正参数,参数正确后匹配白名单 ********/  
  15.   
  16.   
  17.     /********** 判断是GET请求类型 **********/  
  18.     if(req.method.toUpperCase()=="GET"){  
  19.   
  20.         var params=[];  
  21.         //params=url.parse(request.url,true).query;  
  22.         //params['fruit']=compute(params);  
  23.         res.writeHeader(200,{  
  24.             "Content-type":"text/html; charset=utf-8"  
  25.         });  
  26.         res.write('<h1>It is forbidden for the URL request!</h1>');  
  27.         res.write('<hr><address>NodeJs/'+process.version);  
  28.         res.write(' at '+req.headers.host.split(':')[0]);  
  29.         res.write(' Port '+req.headers.host.split(':')[1]+'</address>');  
  30.         res.end();  
  31.   
  32.     }  
  33.     /********* 判断是POST请求类型 **********/  
  34.     else if(req.method.toUpperCase()=='POST'){  
  35.   
  36.         var postData="";  
  37.         /********** 读取Post提交的数据 **********/  
  38.         req.addListener("data",function(data){  
  39.             postData+=data;  
  40.         });  
  41.   
  42.         /********** 数据读取完毕就会执行的监听 *********/  
  43.         req.addListener("end",function(){  
  44.            /********* 定义Post请求主体 *********/  
  45.            var query=require('querystring').parse(postData);  
  46.   
  47.   
  48.            /********** 给客户端返回数据自造JSON **********/  
  49.            function getJson(status){  
  50.                 if(isNaN(status))status=-1;  
  51.                 else{status=Number(status)}  
  52.                 var _drr='{'  
  53.                       +'"status":"1",'  
  54.                       +'"name":"'+query.name+'",'  
  55.                       +'"gender":"'+query.gender+'"}';  
  56.                 var _arr='{'  
  57.                       +'"status":1,'  
  58.                       +'"url":"http://www.liuxinxiu.com/",'  
  59.                       +'"dataList":'  
  60.                       +'{'  
  61.                       +'"siteId":101,'  
  62.                       +'"title":"我的博客||Node Server",'  
  63.                       +'"images":"http://www.liuxinxiu.com/upload/2016/08/10/moren.gif",'  
  64.                       +'"indexNum":"10",'  
  65.                       +'"pageNum":"100000",'  
  66.                       +'"tagNum":"22",'  
  67.                       +'"linkType":"linkTaobao",'  
  68.                       +'"publishTime":"23:15:30"'  
  69.                       +'}'  
  70.                       +'}';  
  71.                 this._dr=JSON.parse(_drr);this._ar=JSON.parse(_arr);  
  72.                 this._dt=this._dr;this._dt.getUser=this._ar;  
  73.            }  
  74.   
  75.            var errStr={"status":-1,"info":"Request Error"};  
  76.   
  77.            /********** 先初步设置头信息,跨域全放开稍后再进行匹配验证 **********/  
  78.            var content_type,content_length,  
  79.            content_type='application/json; charset=utf-8';  
  80.            content_length=Buffer.byteLength(res,'utf8');  
  81.            res.setHeader('Access-Control-Allow-Origin','*');  
  82.            res.setHeader('Access-Control-Allow-Headers','X-Requested-With');  
  83.            res.setHeader('Access-Control-Allow-Methods','GET,POST,PUT,DELETE,OPTIONS');  
  84.            res.setHeader('Content-Type',content_type);  
  85.            res.setHeader('Server','NodeJs/'+process.version);  
  86.   
  87.   
  88.            /************** 判断如果有POST过来规范的数据 *************/  
  89.            if(query.name&&query.gender){  
  90.                 //调用数据  
  91.                 getJson(1);  
  92.   
  93.                 /******** 匹配客户端域名是否在数组列表中 ******/  
  94.                 //if(_self.in_array(origin,allow_origin)){  
  95.                 if(origin.yes){  
  96.                      res.setHeader('Access-Control-Allow-Origin',origin.name);  
  97.                      res.end(JSON.stringify(_dt));  
  98.                 }  
  99.                 else{  
  100.                      /******** 如有设置就取设置URL返回头信息 ********/  
  101.                      if(query.origin){  
  102.                         res.setHeader('Access-Control-Allow-Origin',query.origin);  
  103.                         res.end(JSON.stringify(_dt));  
  104.                      }  
  105.                      /******** 没设置URL就返回无权限错误信息  ********/  
  106.                      else{  
  107.                         errStr.info="You don't have permission to submit!";  
  108.                         res.setHeader('Access-Control-Allow-Origin',origin.name);
  109.                         res.end(JSON.stringify(errStr));
  110.                      }
  111.                 }
  112.            }
  113.            /********* 没有所匹配的POST提交数据||都要设头返回信息 ********/
  114.            else{
  115.                 /******** 其他POST参数的提交  ********/
  116.                 if(query){
  117.                     res.writeHeader(res.statusCode,{
  118.                         "Access-Control-Allow-Origin":origin.name,
  119.                         "Access-Control-Allow-Headers":"X-Requested-With",
  120.                         "Access-Control-Allow-Methods":"GET,POST,PUT,DELETE,OPTIONS",
  121.                         "Content-type":"application/json; charset=utf-8"
  122.                     });
  123.                     var err={status:-1,info:"Syntax error in parameters or arguments."};
  124.                     res.end(JSON.stringify(err));
  125.                 }
  126.                 else{
  127.                     res.writeHeader(res.statusCode,{
  128.                         "Content-type": "text/html; charset=utf-8"
  129.                     });
  130.                     res.end('It is forbidden for the URL request!');  
  131.                 }  
  132.   
  133.             }  
  134.             /****** 判断结束 ******/  
  135.         });  
  136.   
  137.     }  
  138.   
  139.   
  140.   /****** 内部结束 ******/  
  141.   }  
  142. }  
  143. module.exports=new CORS_Node();  

NodeJs数据提交接口地址 (不允许使用GET访问) :http://liuxinxiu.com:3000/CORS_Node/

注意:NodeJs Server 是本站的测试环境,有时候因需要会临时关闭,该地址仅供测试,如您有需要请自建环境~

配合HTML代码如下:

XML/HTML代码
  1. <!DOCTYPE html>  
  2. <html>  
  3. <head>  
  4.     <meta charset="utf-8"/>    
  5.     <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />  
  6.     <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no"/>  
  7.     <meta name="format-detection"content="telephone=no">  
  8.     <meta name="apple-mobile-web-app-capable" content="yes" />  
  9.     <meta name="apple-mobile-web-app-status-bar-style" content="black" />  
  10.     <style>body,html {background:#fff;font-family: "Lucida Grande",Calibri,Arial;font-size:12pt;color: #333;background: #f8f8f8;text-align:center;}*{margin:0;padding:0;}h1{line-height:1.6em;font-size:24px;text-indent:.5em;padding-top:.6em}i{line-height:2em;font-size:18px;color:#999;}.line{height:10px;border-bottom:1px solid #ccc;font-size:0;overflow:hidden;}</style>  
  11.     <title>跨域测试</title>  
  12. </head>  
  13. <body>  
  14. <h1 id="show"></h1>  
  15. <input type="button" value="Click me" onclick="msg()" />  
  16.   
  17. </body>  
  18. <script src="//code.jquery.com/jquery-1.11.3.min.js"></script>  
  19. <script type='text/javascript'>  
  20. /********** 获取URL参数 **********/  
  21. function getQueryString(name){  
  22. var reg=new RegExp("(^|&)"+name+"=([^&]*)(&|$)","i");  
  23. var r=window.location.search.substr(1).match(reg);  
  24. if (r!=null) return unescape(r[2]); return null;  
  25. }  
  26. var _n=getQueryString('n');  
  27. var _url=getQueryString('url');  
  28. var _name=getQueryString('name');  
  29. var _gender=getQueryString('gender');  
  30. var _origin=getQueryString('origin');  
  31. var _error=getQueryString('error');  
  32. console.log('origin:'+_origin+' —— name:'+_name+' —— gender:'+_gender);  
  33.   
  34. window.onload=function(){  
  35.     if(_n=='php'){  
  36.     location.href='http://'  
  37.              +location.host  
  38.              +location.pathname  
  39.              +'?origin=http://'+location.host;  
  40.     }else if(_n=='node'){  
  41.         location.href='http://'  
  42.                      +location.host  
  43.                      +location.pathname  
  44.                      +'?origin=http://'+location.host+'&'  
  45.              +'url=http://liuxinxiu.com:3000/CORS_Node/'  
  46.   
  47.     }else if(_n=='proxy'){  
  48.         location.href='http://'  
  49.                      +location.host  
  50.                      +location.pathname  
  51.                      +'?origin=http://'+location.host+'&'  
  52.                      +'url=http://liuxinxiu.com:3000/CORS_Node_Proxy/'  
  53.       
  54.     }else if(_n=='test'){  
  55.         location.href='http://test1.liuxinxiu.com/php/Interface/html/server.html'  
  56.              +'?origin=http://test1.liuxinxiu.com&'  
  57.              +'url=http://liuxinxiu.com:3000/CORS_Node_Proxy/&'  
  58.              +'error=1'  
  59.     }  
  60. }  
  61.   
  62. /********** 发起Ajax请求 **********/  
  63. function msg(){  
  64.     /******* 动态切换提交数据 *******/  
  65.     if(_origin&&!_error){  
  66.     if(_name&&_gender){  
  67.         var data={name:_name,gender:_gender,origin:_origin};  
  68.     }  
  69.     else{  
  70.         var data={name:"xiaoming",gender:"male",origin:_origin};  
  71.     }  
  72.     }  
  73.     else if(_error==null){  
  74.     var data={name:"xiaoming",gender:"male"};  
  75.     }  
  76.     else if(_error){  
  77.         var data={xxx:111};  
  78.     }  
  79.     /******* 动态设置提交URL *******/  
  80.     if(_url){  
  81.     var urlPath=_url;  
  82.     }  
  83.     else{  
  84.     var urlPath='http://code.liuxinxiu.com/php/Post/CORS_PHP.php';  
  85.     }  
  86.     $.ajax({  
  87.        type:'post',  
  88.        url:urlPath,  
  89.        data:data,  
  90.        cache:false,  
  91.        dataType:'json',  
  92.        success:function(data){  
  93.            if(data.name){  
  94.         document.getElementById("show").innerHTML=data.name+' '+data.gender;  
  95.            }  
  96.        else if(data.status!=1){  
  97.         document.getElementById("show").innerHTML=data.info;  
  98.        }  
  99.        },    
  100.        error:function(){  
  101.            console.log("请求错误//")  
  102.        }  
  103.     });  
  104. };  
  105.   
  106. /***********************************************************************************************  
  107. $.post("http://www.server.com/server.php",{name:"fdipzone",gender:"male"}).done(function(data){    
  108.     document.getElementById("show").innerHTML=data.name+' '+data.gender;  
  109. });  
  110. **********************************************************************************************/  
  111. </script>  
  112. </html>  

HTML访问地址 (测试跨域) ==> http://test1.liuxinxiu.com/php/Interface/html/server.html?n=node

HTML访问地址 (非法参数) ==> http://test1.liuxinxiu.com/php/Interface/html/server.html?error=node

注意:本站的 NodeJs Server 是学习测试环境,有临时关闭的可能,建议在本地环境测试~

Tags: , ,
NodeJs平台 | 评论(0) | 引用(0) | 阅读(3708)