使用NodeJs实现CORS 跨域资源共享,可传参origin通过限制,代码如下:
JavaScript代码
- var http=require('http');
- var origin=require('./origin'); //调用白名单列表
- function CORS_Node(){
- this.exec=function(route,req,res){
- var _self=this;
- /************** 获取客户端origin的域名 **************/
- origin.req=req; //白名单设置置请求头
- origin.yes=origin.listV(); //是否在名单|true
- origin.name=origin.getName(); //客户端ORIGIN
- /******** 先纠正参数,参数正确后匹配白名单 ********/
- /********** 判断是GET请求类型 **********/
- if(req.method.toUpperCase()=="GET"){
- var params=[];
- //params=url.parse(request.url,true).query;
- //params['fruit']=compute(params);
- res.writeHeader(200,{
- "Content-type":"text/html; charset=utf-8"
- });
- res.write('<h1>It is forbidden for the URL request!</h1>');
- res.write('<hr><address>NodeJs/'+process.version);
- res.write(' at '+req.headers.host.split(':')[0]);
- res.write(' Port '+req.headers.host.split(':')[1]+'</address>');
- res.end();
- }
- /********* 判断是POST请求类型 **********/
- else if(req.method.toUpperCase()=='POST'){
- var postData="";
- /********** 读取Post提交的数据 **********/
- req.addListener("data",function(data){
- postData+=data;
- });
- /********** 数据读取完毕就会执行的监听 *********/
- req.addListener("end",function(){
- /********* 定义Post请求主体 *********/
- var query=require('querystring').parse(postData);
- /********** 给客户端返回数据自造JSON **********/
- function getJson(status){
- if(isNaN(status))status=-1;
- else{status=Number(status)}
- var _drr='{'
- +'"status":"1",'
- +'"name":"'+query.name+'",'
- +'"gender":"'+query.gender+'"}';
- var _arr='{'
- +'"status":1,'
- +'"url":"http://www.liuxinxiu.com/",'
- +'"dataList":'
- +'{'
- +'"siteId":101,'
- +'"title":"我的博客||Node Server",'
- +'"images":"http://www.liuxinxiu.com/upload/2016/08/10/moren.gif",'
- +'"indexNum":"10",'
- +'"pageNum":"100000",'
- +'"tagNum":"22",'
- +'"linkType":"linkTaobao",'
- +'"publishTime":"23:15:30"'
- +'}'
- +'}';
- this._dr=JSON.parse(_drr);this._ar=JSON.parse(_arr);
- this._dt=this._dr;this._dt.getUser=this._ar;
- }
- var errStr={"status":-1,"info":"Request Error"};
- /********** 先初步设置头信息,跨域全放开稍后再进行匹配验证 **********/
- var content_type,content_length,
- content_type='application/json; charset=utf-8';
- content_length=Buffer.byteLength(res,'utf8');
- res.setHeader('Access-Control-Allow-Origin','*');
- res.setHeader('Access-Control-Allow-Headers','X-Requested-With');
- res.setHeader('Access-Control-Allow-Methods','GET,POST,PUT,DELETE,OPTIONS');
- res.setHeader('Content-Type',content_type);
- res.setHeader('Server','NodeJs/'+process.version);
- /************** 判断如果有POST过来规范的数据 *************/
- if(query.name&&query.gender){
- //调用数据
- getJson(1);
- /******** 匹配客户端域名是否在数组列表中 ******/
- //if(_self.in_array(origin,allow_origin)){
- if(origin.yes){
- res.setHeader('Access-Control-Allow-Origin',origin.name);
- res.end(JSON.stringify(_dt));
- }
- else{
- /******** 如有设置就取设置URL返回头信息 ********/
- if(query.origin){
- res.setHeader('Access-Control-Allow-Origin',query.origin);
- res.end(JSON.stringify(_dt));
- }
- /******** 没设置URL就返回无权限错误信息 ********/
- else{
- errStr.info="You don't have permission to submit!";
- res.setHeader('Access-Control-Allow-Origin',origin.name);
- res.end(JSON.stringify(errStr));
- }
- }
- }
- /********* 没有所匹配的POST提交数据||都要设头返回信息 ********/
- else{
- /******** 其他POST参数的提交 ********/
- if(query){
- res.writeHeader(res.statusCode,{
- "Access-Control-Allow-Origin":origin.name,
- "Access-Control-Allow-Headers":"X-Requested-With",
- "Access-Control-Allow-Methods":"GET,POST,PUT,DELETE,OPTIONS",
- "Content-type":"application/json; charset=utf-8"
- });
- var err={status:-1,info:"Syntax error in parameters or arguments."};
- res.end(JSON.stringify(err));
- }
- else{
- res.writeHeader(res.statusCode,{
- "Content-type": "text/html; charset=utf-8"
- });
- res.end('It is forbidden for the URL request!');
- }
- }
- /****** 判断结束 ******/
- });
- }
- /****** 内部结束 ******/
- }
- }
- module.exports=new CORS_Node();
NodeJs数据提交接口地址 (不允许使用GET访问) :http://liuxinxiu.com:3000/CORS_Node/
注意:NodeJs Server 是本站的测试环境,有时候因需要会临时关闭,该地址仅供测试,如您有需要请自建环境~
配合HTML代码如下:
XML/HTML代码
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="utf-8"/>
- <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
- <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no"/>
- <meta name="format-detection"content="telephone=no">
- <meta name="apple-mobile-web-app-capable" content="yes" />
- <meta name="apple-mobile-web-app-status-bar-style" content="black" />
- <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>
- <title>跨域测试</title>
- </head>
- <body>
- <h1 id="show"></h1>
- <input type="button" value="Click me" onclick="msg()" />
- </body>
- <script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
- <script type='text/javascript'>
- /********** 获取URL参数 **********/
- function getQueryString(name){
- var reg=new RegExp("(^|&)"+name+"=([^&]*)(&|$)","i");
- var r=window.location.search.substr(1).match(reg);
- if (r!=null) return unescape(r[2]); return null;
- }
- var _n=getQueryString('n');
- var _url=getQueryString('url');
- var _name=getQueryString('name');
- var _gender=getQueryString('gender');
- var _origin=getQueryString('origin');
- var _error=getQueryString('error');
- console.log('origin:'+_origin+' —— name:'+_name+' —— gender:'+_gender);
- window.onload=function(){
- if(_n=='php'){
- location.href='http://'
- +location.host
- +location.pathname
- +'?origin=http://'+location.host;
- }else if(_n=='node'){
- location.href='http://'
- +location.host
- +location.pathname
- +'?origin=http://'+location.host+'&'
- +'url=http://liuxinxiu.com:3000/CORS_Node/'
- }else if(_n=='proxy'){
- location.href='http://'
- +location.host
- +location.pathname
- +'?origin=http://'+location.host+'&'
- +'url=http://liuxinxiu.com:3000/CORS_Node_Proxy/'
- }else if(_n=='test'){
- location.href='http://test1.liuxinxiu.com/php/Interface/html/server.html'
- +'?origin=http://test1.liuxinxiu.com&'
- +'url=http://liuxinxiu.com:3000/CORS_Node_Proxy/&'
- +'error=1'
- }
- }
- /********** 发起Ajax请求 **********/
- function msg(){
- /******* 动态切换提交数据 *******/
- if(_origin&&!_error){
- if(_name&&_gender){
- var data={name:_name,gender:_gender,origin:_origin};
- }
- else{
- var data={name:"xiaoming",gender:"male",origin:_origin};
- }
- }
- else if(_error==null){
- var data={name:"xiaoming",gender:"male"};
- }
- else if(_error){
- var data={xxx:111};
- }
- /******* 动态设置提交URL *******/
- if(_url){
- var urlPath=_url;
- }
- else{
- var urlPath='http://code.liuxinxiu.com/php/Post/CORS_PHP.php';
- }
- $.ajax({
- type:'post',
- url:urlPath,
- data:data,
- cache:false,
- dataType:'json',
- success:function(data){
- if(data.name){
- document.getElementById("show").innerHTML=data.name+' '+data.gender;
- }
- else if(data.status!=1){
- document.getElementById("show").innerHTML=data.info;
- }
- },
- error:function(){
- console.log("请求错误//")
- }
- });
- };
- /***********************************************************************************************
- $.post("http://www.server.com/server.php",{name:"fdipzone",gender:"male"}).done(function(data){
- document.getElementById("show").innerHTML=data.name+' '+data.gender;
- });
- **********************************************************************************************/
- </script>
- </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 是学习测试环境,有临时关闭的可能,建议在本地环境测试~