gulp+apache代理请求处理javascript跨域请求

apache设置(参考)

用 apache 的 mod_proxy 模块开启反向代理功能来实现:

1 修改 apache 配置文件 httpd.conf ,去掉以下两行前面 # 号

    LoadModule proxy_module modules/mod_proxy.so
    LoadModule proxy_http_module modules/mod_proxy_http.so

2 在 server config 或 virtual host 中增加:

    ProxyRequests Off

    <Proxy *>
      Order deny,allow
      Allow from all
    </Proxy>

    ProxyPass /folder http://****.com/floder

重启 apache.

注释:

  • ProxyRequests Off 指令是指采用反向(reverse)代理,对于客户端而言它就像是原始服务器,并且客户端不需要进行任何特别的设置;而正向代理允许客户端通过它访问任意网站并且隐藏客户端自身,因此必须采取安全措施以确保仅为经过授权的客户端提供服务。
  • ProxyPass 指令允许将一个远端服务器映射到本地服务器的 URL 空间中,此时本地服务器并不充当代理角色,而是充当远程服务器的一个镜像。/folder 是一个本地虚拟路径,http://****.com/floder 是一个指向远程服务器的部分 URL

如果不想对某个子目录进行反向代理时,可以用"!"指令。比如说:

    ProxyPass /folder/exception !
    ProxyPass /folder http://****.com/folder

将会代理除 /folder/exception 之外的所有对 http://****.com/floder 的请求。

如访问http://localhost/folder/1.html,apache会将请求变为http://****.com/folder/1.html。ajax的/folder/data.json则会转向http://****.com/folder/data.json

 

gulp server设置:

1 browserSync.init({
2     ui: false,
3     notify: false,
4     port: 5678,
5     // 设置代理请求
6     proxy: 'localhost'
7 })

以上设置之后,browserSync请求http://localhost:5678/index.html,实则会请求地址http://localhost/index.html。

 

 完整gulpfile.js

var gulp = require("gulp")
    , gutil = require("gulp-util")

    , del = require("del")
    , sass = require("gulp-sass")
    , uglify = require('gulp-uglify')
    , rename = require("gulp-rename")

    , browserSync = require("browser-sync").create()
    , reload = browserSync.reload

    , sequence = require("run-sequence")
    , plumber = require("gulp-plumber")
    , watch = require("gulp-watch")

    , through2 = require("through2")
    , path = require("path")
    , fs = require("fs");


// #############################################
// # init params

// 收集参数
var cwd = process.cwd();
var cmdargs = process.argv.slice(2);
var cmdname = cmdargs.shift();
var cmdopts = {};
var srcpath = "./src";
var distpath = "./dist";

while (cmdargs.length) {
    var key = cmdargs.shift().slice(2);
    var val = cmdargs.shift();
    cmdopts[key] = key === "src" || key === "dist" ? normalizePath(val) : val;
}

// 参数配置
var release = cmdname === "release";
var reloadTimer = null;
var devport = 5678;
var paths = {
    src: path.join(__dirname, srcpath),
    dist: path.join(__dirname, distpath)
}

function normalizePath(url) {
    if (url.charAt(0) === "/" || url.indexOf(":") > -1) {
        return path.normalize(url);
    }
    return path.normalize(path.join(cwd, url));
}

function setOptions(cmd, cmdopts) {
    if (cmd === "start") {
        paths.src = cmdopts.src ? path.join(cmdopts.src, srcpath) : paths.src;
    } else if (cmd === "release") {
        paths.src = cmdopts.src ? path.join(cmdopts.src, srcpath) : paths.src;
        paths.dist = cmdopts.dist ? cmdopts.dist : path.normalize(paths.src + "/../" + distpath);
    }
}

function showUsage() {
    console.log("Usage:\n");
    console.log("     gulp                   显示帮助");
    console.log("     gulp help              显示帮助");
    console.log("     gulp start --src src   在--src目录下自动化开发调试环境");
    console.log("     gulp release --src src --dist dist 构建--src线上版本到--dist目录\n");
    console.log("     gulp start --src src --proxy localhost   使用gulp代理localhost请求,并且实时监听src文件修改");
}

// #############################################
// # default tasks

// # clean path
gulp.task("clean:dist", function () {
    return del([paths.dist], {force: true});
});

// # 编译css
gulp.task("sass", function() {
    var base = paths.src;
    var dest = base;
    return gulp.src(base + "/**/*.scss", {base: base})
        .pipe(plumber())
        .pipe(sass({
            precision: 2,
            outputStyle: release ? "compressed" : "expanded"
            //sourceComments: release ? false : true
        })
        .on("error", sass.logError))
        .pipe(gulp.dest(dest));
});


// # 压缩js
gulp.task("uglify", function() {
    var base = paths.src;
    var dest = paths.dist;
    return gulp.src(base + "/**/*.js", {base: base})
        .pipe(plumber())
        .pipe(uglify())
        .pipe(gulp.dest(dest));
});

// # 复制静态资源
gulp.task("copy:dist", function() {
    var base = paths.src;
    var dest = paths.dist;
    return gulp.src([
            base + "/**/*",
            "!" + base + "/**/*.js",
            "!" + base + "/**/*.scss"
        ], {base: base})
        .pipe(gulp.dest(dest));
});


// # serv & watch
gulp.task("server", function() {
    // start server
    browserSync.init({
        ui: false,
        notify: false,
        port: devport,
        // 设置代理请求
        proxy: cmdopts.proxy,
        server: !cmdopts.proxy ? {
            baseDir: paths.src
        } : false
    });

    // # watch src资源, 调用相关任务预处理
    watch(paths.src + "/**/*.scss", function(obj) {
        sequence("sass");
    });

    // # 刷新浏览器
    // # 限制浏览器刷新频率
    watch(paths.src + "/**/*", function(obj) {
        var url = obj.path.replace(/\\/g, "/");
        var absurl = url;
        url = path.relative(paths.src, url);
        console.log("[KS] " + absurl);

        // skip scss
        if (!/\.scss$/.test(url)) {
            if (reloadTimer) {
                clearTimeout(reloadTimer);
            }
            reloadTimer = setTimeout(reload, 1000);
        }
    });
});


// #############################################
// # public task

gulp.task("default", showUsage);
gulp.task("help", showUsage);

gulp.task("start", function(cb) {
    release = false;
    setOptions("start", cmdopts);
    sequence("sass", "server", cb);
});

gulp.task("release", function(cb) {
    release = true;
    setOptions("release", cmdopts);
    sequence("clean:dist", ["sass", "uglify"], "copy:dist", cb);
});
View Code

windows bat命令文件:

C:
cd D:\iwork\www\work\www-front\dev-specs
D:
:: 不使用代理请求
:: gulp start --src ../m/zt/2016/h5/olympic
:: 使用代理请求
gulp start --src ../m/zt/2016/h5/olympic --proxy http://localhost/work/www-front/m/zt/2016/h5/olympic/src/
View Code

 

 

 

posted @ 2016-07-29 12:33  极·简  Views(1424)  Comments(0Edit  收藏  举报