Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use proxy middleware with gulp connect

I am trying to use gulp-connect to forward all requests to api/ to localhost:3000. I found an example at https://github.com/AveVlad/gulp-connect/issues/27

and setup my connect task like this:

gulp.task('connect', function(){
    connect.server({
        root: './app', 
    middleware: function(connect, o) {
      return [ (function() {
        var url = require('url');
        var proxy = require('proxy-middleware');
        var options = url.parse('http://localhost:3000/api');
        options.route = 'api';
        return proxy(options);
      })()]
    }
    });
});

Running this task warns that connect deprecated connect(middleware): use app.use(middleware) instead node_modules/gulp-connect/index.js:39:19 and this task does not forward requests as expected.

I looked at the connect source to see if I could work around the depreciation, but it is beyond my level in js:

 ConnectApp.prototype.server = function() {
    var app, middleware;
    middleware = this.middleware();
    app = connect.apply(null, middleware);
    server = http.createServer(app);
    app.use(connect.directory(typeof opt.root === "object" ? opt.root[0] : opt.root));
    server.listen(opt.port);
    this.log("Server started http://" + opt.host + ":" + opt.port);
    if (opt.livereload) {
      tiny_lr.Server.prototype.error = function() {};
      lr = tiny_lr();
      lr.listen(opt.livereload.port);
      return this.log("LiveReload started on port " + opt.livereload.port);
    }
  };

I cannot figure out how to change my gulp-file to use app.use(middleware), the app variable is not exported by the connect module.

like image 798
user2936314 Avatar asked Jul 03 '14 06:07

user2936314


1 Answers

A solution given by chimurai on Github is to use the http-proxy-middleware package to do that.

For example :

var gulp = require('gulp');
var connect = require('gulp-connect');
var proxy = require('http-proxy-middleware');

gulp.task('connect', function() {
    connect.server({
        root: ['./app'],
        middleware: function(connect, opt) {
            return [
                proxy('/api', {
                    target: 'http://localhost:3000',
                    changeOrigin:true
                })
            ]
        }

    });
});

gulp.task('default', ['connect']);
like image 164
Blackus Avatar answered Oct 06 '22 00:10

Blackus