cors 的js

获取cors,获得的是一个函数,执行返回一个中间件
(function () {

  'use strict';

  var assign = require('object-assign');
  var vary = require('vary');

  var defaults = {
    origin: '*',
    methods: 'GET,HEAD,PUT,PATCH,POST,DELETE',
    preflightContinue: false,
    optionsSuccessStatus: 204
  };

  function isString(s) {
    return typeof s === 'string' || s instanceof String;
  }

  function isOriginAllowed(origin, allowedOrigin) {
    if (Array.isArray(allowedOrigin)) {
      for (var i = 0; i < allowedOrigin.length; ++i) {
        if (isOriginAllowed(origin, allowedOrigin[i])) {
          return true;
        }
      }
      return false;
    } else if (isString(allowedOrigin)) {
      return origin === allowedOrigin;
    } else if (allowedOrigin instanceof RegExp) {
      return allowedOrigin.test(origin);
    } else {
      return !!allowedOrigin;
    }
  }

  function configureOrigin(options, req) {
    var requestOrigin = req.headers.origin,
      headers = [],
      isAllowed;

    if (!options.origin || options.origin === '*') {
      // allow any origin
      headers.push([{
        key: 'Access-Control-Allow-Origin',
        value: '*'
      }]);
    } else if (isString(options.origin)) {
      // fixed origin
      headers.push([{
        key: 'Access-Control-Allow-Origin',
        value: options.origin
      }]);
      headers.push([{
        key: 'Vary',
        value: 'Origin'
      }]);
    } else {
      isAllowed = isOriginAllowed(requestOrigin, options.origin);
      // reflect origin
      headers.push([{
        key: 'Access-Control-Allow-Origin',
        value: isAllowed ? requestOrigin : false
      }]);
      headers.push([{
        key: 'Vary',
        value: 'Origin'
      }]);
    }

    return headers;
  }

  function configureMethods(options) {
    var methods = options.methods;
    if (methods.join) {
      methods = options.methods.join(','); // .methods is an array, so turn it into a string
    }
    return {
      key: 'Access-Control-Allow-Methods',
      value: methods
    };
  }

  function configureCredentials(options) {
    if (options.credentials === true) {
      return {
        key: 'Access-Control-Allow-Credentials',
        value: 'true'
      };
    }
    return null;
  }

  function configureAllowedHeaders(options, req) {
    var allowedHeaders = options.allowedHeaders || options.headers;
    var headers = [];

    if (!allowedHeaders) {
      allowedHeaders = req.headers['access-control-request-headers']; // .headers wasn't specified, so reflect the request headers
      headers.push([{
        key: 'Vary',
        value: 'Access-Control-Request-Headers'
      }]);
    } else if (allowedHeaders.join) {
      allowedHeaders = allowedHeaders.join(','); // .headers is an array, so turn it into a string
    }
    if (allowedHeaders && allowedHeaders.length) {
      headers.push([{
        key: 'Access-Control-Allow-Headers',
        value: allowedHeaders
      }]);
    }

    return headers;
  }

  function configureExposedHeaders(options) {
    var headers = options.exposedHeaders;
    if (!headers) {
      return null;
    } else if (headers.join) {
      headers = headers.join(','); // .headers is an array, so turn it into a string
    }
    if (headers && headers.length) {
      return {
        key: 'Access-Control-Expose-Headers',
        value: headers
      };
    }
    return null;
  }

  function configureMaxAge(options) {
    var maxAge = (typeof options.maxAge === 'number' || options.maxAge) && options.maxAge.toString()
    if (maxAge && maxAge.length) {
      return {
        key: 'Access-Control-Max-Age',
        value: maxAge
      };
    }
    return null;
  }

  function applyHeaders(headers, res) {
    for (var i = 0, n = headers.length; i < n; i++) {
      var header = headers[i];
      if (header) {
        if (Array.isArray(header)) {
          applyHeaders(header, res);
        } else if (header.key === 'Vary' && header.value) {
          vary(res, header.value);
        } else if (header.value) {
          res.setHeader(header.key, header.value);
        }
      }
    }
  }

  function cors(options, req, res, next) {
    var headers = [],
      method = req.method && req.method.toUpperCase && req.method.toUpperCase();

    if (method === 'OPTIONS') {
      // preflight
      headers.push(configureOrigin(options, req));
      headers.push(configureCredentials(options, req));
      headers.push(configureMethods(options, req));
      headers.push(configureAllowedHeaders(options, req));
      headers.push(configureMaxAge(options, req));
      headers.push(configureExposedHeaders(options, req));
      applyHeaders(headers, res);

      if (options.preflightContinue) {
        next();
      } else {
        // Safari (and potentially other browsers) need content-length 0,
        //   for 204 or they just hang waiting for a body
        res.statusCode = options.optionsSuccessStatus;
        res.setHeader('Content-Length', '0');
        res.end();
      }
    } else {
      // actual response
      headers.push(configureOrigin(options, req));
      headers.push(configureCredentials(options, req));
      headers.push(configureExposedHeaders(options, req));
      applyHeaders(headers, res);
      next();
    }
  }

  function middlewareWrapper(o) {
    // if options are static (either via defaults or custom options passed in), wrap in a function
    var optionsCallback = null;
    if (typeof o === 'function') {
      optionsCallback = o;
    } else {
      optionsCallback = function (req, cb) {
        cb(null, o);
      };
    }

    return function corsMiddleware(req, res, next) {
      optionsCallback(req, function (err, options) {
        if (err) {
          next(err);
        } else {
          var corsOptions = assign({}, defaults, options);
          var originCallback = null;
          if (corsOptions.origin && typeof corsOptions.origin === 'function') {
            originCallback = corsOptions.origin;
          } else if (corsOptions.origin) {
            originCallback = function (origin, cb) {
              cb(null, corsOptions.origin);
            };
          }

          if (originCallback) {
            originCallback(req.headers.origin, function (err2, origin) {
              if (err2 || !origin) {
                next(err2);
              } else {
                corsOptions.origin = origin;
                cors(corsOptions, req, res, next);
              }
            });
          } else {
            next();
          }
        }
      });
    };
  }

  // can pass either an options hash, an options delegate, or nothing
  module.exports = middlewareWrapper;

}());

 

也有这种导出具体对象的~  

 

/**

 * Module exports.

 */

 

module.exports = vary

module.exports.append = append

 

也有这种暴露对象的

 

var server = httpServer.createServer(options);

httpServer = require('../lib/http-server')

 

module.exrpots = {

   a:a

   b:b
}

 

//rule scheme :

module.exports = {

    replaceRequestOption : function(req,option){
        //replace request towards http://www.taobao.com 
        //                     to http://www.taobao.com/about/

        /*
        option scheme:
        {
            hostname : "www.taobao.com"
            port     : 80
            path     : "/"
            method   : "GET"
            headers  : {cookie:""}
        }
        */
       option.headers["User-Agent"]="Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.111 Safari/537.36"
    },
    printLog : function printLog(content,type){
        //no log any more
    }
};

 

// open jone.yb.com , execute this script in console, then have a tea

$("#JONE-SXGL-DBSQSQCX").click();

function range(start, count) {
    return Array.apply(0, Array(count))
                .map(function (element, index) {
                         return index + start;
                     });
}


(function(db_count, instance_count, page_limit){
  ip_list = ['172.20.132.11', '172.20.132.13', '172.20.132.15', '172.20.132.17''];
  var num = db_count / instance_count;
  setTimeout(function(){
    //step 1, open db auth list
    dbAuthViewListJS.toAddPage();

    console.log('db_count:' + db_count);
    console.log('instance_count:' + instance_count);
    console.log('count:' + (parseInt(db_count / page_limit) + 1));
    $.each(range(1, parseInt(db_count / page_limit) + 1), function(i, v) {
      //step 2, open new auth page
      (function(page){
        setTimeout(function(){
          dbAuthViewListJS.toAddPage();
          //step 3, fill form
          setTimeout(function(){
            // 申请标题
            $("#dbAuthApplyTopic").val('jproxy访问poporder权限申请');

            // 数据库地址
            var end = page_limit*(page+1) > db_count ? db_count : page_limit*(page+1);
            var l = range(page_limit*page, page_limit).map(function(val){
              if(val >= db_count) {
                return undefined;
              }
              var db = {};
              db.ip = ip_list[parseInt(val/num)];
              db.port = '3358';
              db.name = 'poporder_' + val;
              return db;
            });

            $.each(l, function(i, db){
              if (db) {
                $("#dbServerIp").val(db.ip);
                $("#dbPort").val(db.port);
                $("#dbName").val(db.name);
                console.log(db);
                dbAuthAddJS.addDbInfo();
              }
            });

            // 选择应用
            $("#appId option[value='9741']").attr('selected', true);
            dbAuthAddJS.showSelectIpGroupModal();
            setTimeout(function(){
              // 分组/IP选择...
              $("#appGroup option[value='15655']").attr('selected', true);
              dbAuthAddJS.changeGroup();
              setTimeout(function(){
                // IP
                $("#ipUnselected option[value='172.22.70.39']").attr('selected', true);
                $("#ipUnselected option[value='172.22.70.40']").attr('selected', true);
                $("#ipUnselected option[value='172.22.70.41']").attr('selected', true);
                $("#ipUnselected option[value='172.22.71.115']").attr('selected', true);
                $("#ipUnselected option[value='172.22.71.116']").attr('selected', true);
                $("#ipUnselected option[value='172.22.71.117']").attr('selected', true);
                $("#ipUnselected option[value='172.22.71.118']").attr('selected', true);
                dbAuthAddJS.selectIp();
                setTimeout(function(){
                  $("button.close").click();
                  // 参考应用
                  $("#refAppId option[value='9741']").attr('selected', true);
                  dbAuthAddJS.getRefGroup();
                  setTimeout(function(){
                    // 参考组
                    $("#refGroup option[value='15655']").attr('selected', true);
                    dbAuthAddJS.getRefGroupIp();
                    setTimeout(function(){
                      // 参考IP
                      $("#refGroupIp option[deploy-host-ip='172.22.70.39']").attr('selected', true);

                      // 提交
                      dbAuthAddJS.submit();
                      // dbAuthAddJS.toListPage();
                      setTimeout(function(){
                        // 确认结果
                        $('#windowAlertModal').modal('hide');
                      }, 5000);
                    }, 2000);
                  }, 2000);
                }, 1000);
              }, 2000);
            }, 2000);
          }, 2000);
        }, page * 25000);
      })(i);
    });
  }, 3000);
})(1024, 16, 30);

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值