javascript 使用代理服务器设置gulp示例

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript 使用代理服务器设置gulp示例相关的知识,希望对你有一定的参考价值。

'use strict';

var path = require('path');
var gulp = require('gulp');
var conf = require('./conf');
var fs = require('fs');

var browserSync = require('browser-sync');
var browserSyncSpa = require('browser-sync-spa');

var util = require('util');

var proxyMiddleware = require('http-proxy-middleware');

function browserSyncInit(baseDir, browser) {
  browser = browser === undefined ? 'default' : browser;

  var routes = null;
  if(baseDir === conf.paths.src || (util.isArray(baseDir) && baseDir.indexOf(conf.paths.src) !== -1)) {
    routes = {
      '/bower_components': 'bower_components'
    };
  }

  var server = {
    baseDir: baseDir,
    routes: routes
  };

  /*
   * You can add a proxy to your backend by uncommenting the line below.
   * You just have to configure a context which will we redirected and the target url.
   * Example: $http.get('/users') requests will be automatically proxified.
   *
   * For more details and option, https://github.com/chimurai/http-proxy-middleware/blob/v0.9.0/README.md
   */
  server.middleware = [];
  server.middleware.push(proxyMiddleware('/v1', {target: 'http://0.0.0.0:3000', changeOrigin: true}));
  server.middleware.push(function (req, res, next) {
    if (req.url.indexOf('/mock/') !== 0) {
      next();
      return;
    }
    var filename = path.resolve(__dirname, '..', 'mock', req.url.replace(/^\/mock\//, ''));
    res.setHeader('Content-Type', 'application/json');
    fs.createReadStream(filename).pipe(res);
  });

  browserSync.instance = browserSync.init({
    startPath: '/',
    server: server,
    browser: browser,
    ui: {
      port: 4001
    },
    port: 4000
  });
}

browserSync.use(browserSyncSpa({
  selector: '[ng-app]'// Only needed for angular apps
}));

gulp.task('serve', ['watch'], function () {
  browserSyncInit([path.join(conf.paths.tmp, '/serve'), conf.paths.src]);
});

gulp.task('serve:dist', ['build'], function () {
  browserSyncInit(conf.paths.dist);
});

gulp.task('serve:e2e', ['inject'], function () {
  browserSyncInit([conf.paths.tmp + '/serve', conf.paths.src], []);
});

gulp.task('serve:e2e-dist', ['build'], function () {
  browserSyncInit(conf.paths.dist, []);
});

以上是关于javascript 使用代理服务器设置gulp示例的主要内容,如果未能解决你的问题,请参考以下文章

Laravel(@ 8000)+ Angular with Gulp(@ 9000),如何在请求9000时让gulp代理8000端口?

npm 使用代理 install 插件

简单的gulp构建实例+代理服务器

代理URL不能与BrowserSync Gulp任务一起使用

javascript 适用于WordPress的Gulp设置代码段也可用于前端开发

如何修改chrome代理服务器