Giter VIP home page Giter VIP logo

grunt-connect-proxy's Introduction

grunt-connect-proxy

Provides a http proxy as middleware for the grunt-contrib-connect plugin.

Getting Started

This plugin requires Grunt ~0.4.1

If you haven't used Grunt before, be sure to check out the Getting Started guide, as it explains how to create a Gruntfile as well as install and use Grunt plugins. Once you're familiar with that process, you may install this plugin with this command:

npm install grunt-connect-proxy --save-dev

One the plugin has been installed, it may be enabled inside your Gruntfile with this line of JavaScript:

grunt.loadNpmTasks('grunt-connect-proxy');

Adapting the "connect" task

Overview

Proxy Configuration

In your project's Gruntfile, add a section named proxies to your existing connect definition.

grunt.initConfig({
    connect: {
        server: {
            options: {
                port: 9000,
                hostname: 'localhost'
            },
            proxies: [
                {
                    context: '/cortex',
                    host: '10.10.2.202',
                    port: 8080,
                    https: false,
                    xforward: false,
                    headers: {
                        "x-custom-added-header": value
                    },
                    hideHeaders: ['x-removed-header']
                }
            ]
        }
    }
})

Adding the middleware

With Livereload

Add the middleware call from the connect option middleware hook

        connect: {
            livereload: {
                options: {
                    middleware: function (connect, options) {
                        if (!Array.isArray(options.base)) {
                            options.base = [options.base];
                        }

                        // Setup the proxy
                        var middlewares = [require('grunt-connect-proxy/lib/utils').proxyRequest];

                        // Serve static files.
                        options.base.forEach(function(base) {
                            middlewares.push(connect.static(base));
                        });

                        // Make directory browse-able.
                        var directory = options.directory || options.base[options.base.length - 1];
                        middlewares.push(connect.directory(directory));

                        return middlewares;
                    }
                }
            }
        }
Without Livereload

It is possible to add the proxy middleware without Livereload as follows:

   // server
    connect: {
      server: {
        options: {
          port: 8000,
          base: 'public',
          logger: 'dev',
          hostname: 'localhost',
          middleware: function (connect, options, defaultMiddleware) {
             var proxy = require('grunt-connect-proxy/lib/utils').proxyRequest;
             return [
                // Include the proxy first
                proxy
             ].concat(defaultMiddleware);
          }
        },
        proxies: [ /* as defined above */ ]
      }
  }

Adding the configureProxy task to the server task

For the server task, add the configureProxies task before the connect task

    grunt.registerTask('server', function (target) {
        grunt.task.run([
            'clean:server',
            'compass:server',
            'configureProxies:server',
            'livereload-start',
            'connect:livereload',
            'open',
            'watch'
        ]);
    });

IMPORTANT: You must specify the connect target in the configureProxies task.

Options

The available configuration options from a given proxy are generally the same as what is provided by the underlying httpproxy library

options.context

Type: String or Array

The context(s) to match requests against. Matching requests will be proxied. Should start with /. Should not end with / Multiple contexts can be matched for the same proxy rule via an array such as: context: ['/api', '/otherapi']

options.host

Type: String

The host to proxy to. Should not start with the http/https protocol.

options.port

Type: Number Default: 80

The port to proxy to.

options.https

Type: Boolean Default: false

if the proxy should target a https end point on the destination server

options.secure

Type: Boolean Default: true

true/false, if you want to verify the SSL Certs (Avoids: SELF_SIGNED_CERT_IN_CHAIN errors when set to false)

Whether to proxy with https

options.xforward:

Type: Boolean Default: false

Whether to add x-forward headers to the proxy request, such as "x-forwarded-for": "127.0.0.1", "x-forwarded-port": 50892, "x-forwarded-proto": "http"

options.appendProxies

Type: Boolean Default: true

Set to false to isolate multi-task configuration proxy options from parent level instead of appending them.

options.rewrite

Type: Object

Allows rewrites of url (including context) when proxying. The object's keys serve as the regex used in the replacement operation. As an example the following proxy configuration will update the context when proxying:

proxies: [
    context: '/context',
    host: 'host',
    port: 8080,
    rewrite: {
        '^/removingcontext': '',
        '^/changingcontext': '/anothercontext',
        '^/updating(context)': function(match, p1) {
            return '/new' + p1;
        }
    }
]

options.headers

Type: Object

A map of headers to be added to proxied requests.

options.hostRewrite

Type: String

Rewrites the location hostname on 30X redirects.

options.hideHeaders

Type: Array

An array of headers that should be removed from the server's response.

options.errorHandler

Type: Function

Another middleware that will be called if proxy request fails. Example:

    errorHandler: function(req, res, next, err) {
        if (err.code === 404) {
            res.send('Some error page');
        } else {
            next();
        }
    }

options.ws

Type: Boolean Default: false

Set to true to proxy websockets.

Contributing

In lieu of a formal styleguide, take care to maintain the existing coding style. Add unit tests for any new or changed functionality. Lint and test your code using Grunt.

Multi-server proxy configuration

grunt-contrib-connect multi-server configuration is supported. You can define proxies blocks in per-server options and refer to those blocks in task invocation.

grunt.initConfig({
    connect: {
            options: {
                port: 9000,
                hostname: 'localhost'
            },
            server2: {
                proxies: [
                    {
                        context: '/cortex',
                        host: '10.10.2.202',
                        port: 8080,
                        https: false,
                    }
                ]
            },
            server3: {
                appendProxies: false,
                proxies: [
                    {
                        context: '/api',
                        host: 'example.org'
                    }
                ]
            }
        }
})

grunt.registerTask('e2etest', function (target) {
    grunt.task.run([
        'configureProxies:server2',
        'open',
        'karma'
    ]);
});

Release History

  • 0.1.0 Initial release
  • 0.1.1 Fix changeOrigin
  • 0.1.2 Support multiple server definitions, bumped to grunt 0.4.1 (thanks to @lauripiispanen)
  • 0.1.3 Bumped http-proxy dependency to 0.10.2
  • 0.1.4 Added proxy rewrite support (thanks to @slawrence)
  • 0.1.5 Default rejectUnauthorized to false to allow self-signed certificates over SSL
  • 0.1.6 Add xforward option, added support for context arrays, added debug logging
  • 0.1.7 Added WebSocket support (thanks for @killfill), Headers support (thanks to @gadr), various docs fixed
  • 0.1.8 Minor websocket bug fix
  • 0.1.10 Minor bug fix
  • 0.1.11 Fix Websocket support on Node 0.10 - Bumped http-proxy dependency to 1.1.4, Removed unsupported http-proxy options (rejectUnauthorized, timeout, changeOrigin)
  • 0.2.0 Added hidden headers support

grunt-connect-proxy's People

Contributors

abanctelchevrel avatar chadkillingsworth avatar chicoxyzzy avatar cinaglia avatar drewzboto avatar eddiemonge avatar flaviogranero avatar guifromrio avatar killfill avatar krotscheck avatar lalem001 avatar matthieubulte avatar olysyuk avatar ruiaraujo avatar shairez avatar slawrence avatar tschaub avatar yamsellem avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

grunt-connect-proxy's Issues

Config not working.

I am having quite a bit of trouble getting grunt-connect-proxy working properly. Based on my current grunt file I see through terminal that the proxy has been set up with the message:

Running "configureProxies:server" (configureProxies) task
Proxy created for: /api to localhost:8000

However, all requests to /api are still routing through localhost:9000 which is the express server the angular app is running on rather than port 8000 which they proxy was created for. Here is a link to my gruntfile:

https://gist.github.com/JohnBueno/7d48027f739cc91e0b79

Would it be possible to update examples/sample.yeoman.grunt.js to match the new config documented in the readme?

Any help on this would be much appreciated!

"Fatal error" when accentuated characters in partials

I'm using grunt-connect-proxy to simulate a baseUrl on my Angular application (generated with Yeoman), with the following config :

      proxies: [
        {
          context: '/context',
          host: 'localhost',
          port: 9000,
          rewrite: {
            '^/context': ''
          }
        }
      ],

I run grunt server --debug to launch my dev server on localhost:9000 .
This way, when I visit localhost:9000/context it actually displays the app hosted at localhost:9000 .
It works well, aside from the fact that when my app loads a partial (using ng-include) containing an accentuated character, the servers stops abruptly with the message Fatal error: Can't render headers after they are sent to the client.

When I strip the accentuated character from the partial everything is OK.

I will try to push a simple setup to reproduce the bug when I have time, but in the meantime do you have any clue of what is going wrong ?

NB: I'm using node v0.10.10

documentation bug: example code for proxy config shows "server" key

The latest version does not have "server" as key for "options". It should show:
grunt.initConfig({
connect: {
options: {
port: 9000,
// Change this to '0.0.0.0' to access the server from outside.
hostname: 'localhost',
livereload: 35729
},
...
...
}

Notice that there is no "server" as key for options. Same goes for Without Livereload example as well

Error with grunt-contrib-connect 0.8.0

This plugin is broken in usage with grunt connect 0.8.0, updating to this version will result in the following error:

Running "connect:devproxy" (connect) task
Verifying property connect.devproxy exists in config...OK
File: [no files]
Options: protocol="http", port=9997, hostname="closedhost", base="tmp", directory=null, keepalive=false, debug=false, livereload, open=false, useAvailablePort=false,onCreateServer=null, middleware=undefined
Warning: Arguments to path.resolve must be strings Use --force to continue.

Please fix. :)

Best Regards,

@zenhunt

How to connect to multiple servers?

Hi there!

First of all: Great tool! Really reduced my proxy setup time from about a half day of Apache configuration to half a minute of simply adding a task. So big thumbs up for that!

But now I've the use-case of directing to two different servers in one run, and I tried to create this something like that:

           server: {
                proxies: [
                    {
                        context: '/',
                        host: 'subdomain1.someserver.com',
                        changeOrigin: true
                    },{
                        context: '/websrv',
                        host: 'subdomain2.someserver.com'
                    }
                ]
            },

So i can use

localhost:9000/someservice which proxies to http://subdomain1.someserver.com/someservice (which works great), and localhost:9000/websrv which proxies to http://subdomain2.someserver.com/

Am I on the right track or completely missing the points of contexts and all?

Also tried multi-proxy like in your documentation, but with that it's also not possible to run both proxies at the same time, isn't it?

REST- Body Request Example & Support

Hi,

My situation: I'd like to have a mock-server to match REST-Verbs:

How about matching specific parameters inside a body like
when sending a POST Request with a specific ID,
I'd like to redirect it to a file with this concrete ID

An example or support would be nice!

use grunt-connect-proxy forward from port 80 to 3000

After install and running mean.js on my linux vm, I wanted to use mycompany.com to forward to ipaddress:3000 using grunt-connect-proxy. I get error "connection refused", even when I do curl on the same linux vm. Thinking it might be due to incorrect configuration of my DNS registration, I did try with ipaddress, still no luck. Can some one please help me with proxy forwarding with mean and grunt. I did go through documentation of grunt-connect-proxy and its not clear enough. I must be making some simple mistake in my grunt configuration, here is the gruntfile.js content,

var proxySnippet = require('grunt-connect-proxy/lib/utils').proxyRequest;

var lrSnippet = require('grunt-contrib-livereload/lib/utils').livereloadSnippet;

module.exports = function(grunt) {

// Unified Watch Object

var watchFiles = {

serverViews: ['app/views//.'],

serverJS: ['gruntfile.js', 'server.js', 'config//*.js', 'app//*.js'],

clientViews: ['public/modules//views//*.html'],

clientJS: ['public/js/.js', 'public/modules/__/.js'],

clientCSS: ['public/modules/*/.css'],

mochaTests: ['app/tests/*/.js']

};

// Project Configuration

grunt.initConfig({

pkg: grunt.file.readJSON('package.json'),

connect: {

server: {

                                        options: {

                                                port: 80,

                                                hostname: '0.0.0.0'

                                        },

                                        proxies: [

                                                        {

                                                        context: '/',

                                                        host: 'localhost:3000',

                                                        changeOrigin: true

                                                        }

                                                ]

},

livereload: {

options: {

                                                  open: 'http://localhost:3000',

middleware: function (connect) {

return [

lrSnippet,

mountFolder(connect, '.tmp'),

mountFolder(connect, yeomanConfig.app),

proxySnippet

];

}

}

}

},

forever: {

  server1: {

options: {

index: 'server.js',

logDir: 'logs'

}

 }

},

watch: {

serverViews: {

files: watchFiles.serverViews,

options: {

livereload: true

}

},

serverJS: {

files: watchFiles.serverJS,

tasks: ['jshint'],

options: {

livereload: true

}

},

clientViews: {

files: watchFiles.clientViews,

options: {

livereload: true,

}

},

clientJS: {

files: watchFiles.clientJS,

tasks: ['jshint'],

options: {

livereload: true

}

},

clientCSS: {

files: watchFiles.clientCSS,

tasks: ['csslint'],

options: {

livereload: true

}

}

},

jshint: {

all: {

src: watchFiles.clientJS.concat(watchFiles.serverJS),

options: {

jshintrc: true

}

}

},

csslint: {

options: {

csslintrc: '.csslintrc',

},

all: {

src: watchFiles.clientCSS

}

},

uglify: {

production: {

options: {

mangle: false

},

files: {

'public/dist/application.min.js': 'public/dist/application.js'

}

}

},

cssmin: {

combine: {

files: {

'public/dist/application.min.css': '<%= applicationCSSFiles %>'

}

}

},

nodemon: {

dev: {

script: 'server.js',

options: {

nodeArgs: ['--debug'],

ext: 'js,html',

watch: watchFiles.serverViews.concat(watchFiles.serverJS)

}

}

},

'node-inspector': {

custom: {

options: {

'web-port': 1337,

'web-host': 'localhost',

'debug-port': 5858,

'save-live-edit': true,

'no-preload': true,

'stack-trace-limit': 50,

'hidden': []

}

}

},

            ngmin: {

                production: {

                    files: {

                        'public/dist/application.js': '<%= applicationJavaScriptFiles %>'

                    }

                }

            },

concurrent: {

default: ['nodemon', 'watch'],

debug: ['nodemon', 'watch', 'node-inspector'],

options: {

logConcurrentOutput: true

}

},

env: {

test: {

NODE_ENV: 'test'

}

},

mochaTest: {

src: watchFiles.mochaTests,

options: {

reporter: 'spec',

require: 'server.js'

}

},

karma: {

unit: {

configFile: 'karma.conf.js'

}

}

});

// Load NPM tasks

require('load-grunt-tasks')(grunt);

// Making grunt default to force in order not to break the project.

grunt.option('force', true);

// A Task for loading the configuration object

grunt.task.registerTask('loadConfig', 'Task that loads the config into a grunt option.', function() {

var init = require('./config/init')();

var config = require('./config/config');

grunt.config.set('applicationJavaScriptFiles', config.assets.js);

grunt.config.set('applicationCSSFiles', config.assets.css);

});

    grunt.loadNpmTasks('grunt-contrib-watch');

    grunt.loadNpmTasks('grunt-connect-proxy');

    grunt.loadNpmTasks('grunt-forever');

// Default task(s).

grunt.registerTask('default', ['lint', 'concurrent:default','configureProxies', 'connect:livereload']);

// Debug task.

grunt.registerTask('debug', ['lint', 'concurrent:debug']);

// Lint task(s).

grunt.registerTask('lint', ['jshint', 'csslint']);

// Build task(s).

grunt.registerTask('build', ['lint', 'loadConfig', 'ngmin', 'uglify', 'cssmin']);

// Test task.

grunt.registerTask('test', ['env:test', 'mochaTest', 'karma:unit']);

How to proxy to a different context?

Hi,
I'm using grunt server to open up a livereload server on localhost:9000
my current proxy setup is:

context: "/api" ,
host: "localhost",
port: "8080"

When I go to localhost:9000/api it tries to go to "localhost:8080/api`

How can I just proxy to localhost:8080 without the context of /api on the target server?

TypeError: Cannot read property 'verbose' of undefined

When i'm running my tests in Travis CI, i'm getting the following error and I tried very hard to look at the code and couldn't find where utils.log should come from. I'm wondering if i'm missing something in configuration file or so. Thanks!

TypeError: Cannot read property 'verbose' of undefined
    at enableWebsocket (/.../node_modules/grunt-connect-proxy/lib/utils.js:101:18)
    at Object.utils.proxyRequest [as handle] (/.../node_modules/grunt-connect-proxy/lib/utils.js:109:5)
    at next (/.../node_modules/grunt-contrib-connect/node_modules/connect/lib/proto.js:190:15)
    at resume (/.../node_modules/grunt-contrib-connect/node_modules/connect/lib/middleware/static.js:60:7)
    at SendStream.error (/.../node_modules/grunt-contrib-connect/node_modules/connect/lib/middleware/static.js:73:37)
    at SendStream.EventEmitter.emit (events.js:95:17)
    at SendStream.error (/.../node_modules/grunt-contrib-connect/node_modules/connect/node_modules/send/lib/send.js:147:51)
    at SendStream.onStatError (/.../node_modules/grunt-contrib-connect/node_modules/connect/node_modules/send/lib/send.js:248:48)
    at /.../node_modules/grunt-contrib-connect/node_modules/connect/node_modules/send/lib/send.js:320:26
    at Object.oncomplete (fs.js:107:15)

Trying to proxy to api.githib.com

Hello,

I am trying to proxy requests from /api to https://api.github.com but keep getting redirected to http://developer.github.com.

Curl requests to http://localhost/api return a 301 redirect pointing to http://developer.github.com whereas curl requests direct to https://api.github.com return 200 success and the expected content.

Below is proxy my configuration. The lvh version is working fine. Any suggestions on what I might be missing?

proxies: [
  {
    context: '/api',
    host: 'api.github.com',
    port: 443,
    https: true,
    changeOrigin: true,
    rejectUnauthorized: false,
    rewrite: {
      '^/api': ''
    }
  },
  {
    context: '/lvh',
    host: 'api.lvh.me',
    port: 3030,
    https: false,
    changeOrigin: false,
    rewrite: {
      '^/lvh': ''
    }
  }
]

Proxies not used on Heroku

I seem to be having an issue where my proxies do not get picked on Heroku, but work great locally.

Instead on Heroku all requests expected to get proxied just get routed to my Heroku app.

Here is our grunt setup:

var proxyRequest = require('grunt-connect-proxy/lib/utils').proxyRequest;
// Heroku port
var port = process.env.PORT || 3000;

grunt.initConfig({
  connect: {
      server: {
        options: {
          hostname: 'localhost',
          port: 3000,
          base: 'app/',
          debug: true,
          middleware: function (connect, options) {
            return [
              // Configure proxies
              proxyRequest,

              // Serve static files
              connect(connect.static(options.base)).listen(port)
            ];
          }
        },
        proxies: [
          {
            context: '/api',
            host: 'some.proxy.com',
            port: 80,
            https: false,
            changeOrigin: true,
            xforward: false,
          rewrite: {
            '^/api': ''
          }
        }
      ]
    }
  }
});

Subdomain matching as well as url/path?

Hey there! Is it possible to check for and proxy a request subdomain match as well as a match to a specific path? I've got my grunt server command set to open app.lvh.me:9000 - with lvh.me redirecting to localhost - and I'm querying a rails API on localhost:3000 at api.lvh.me:9000.

The goal is to redirect api.lvh.me:9000 to localhost:3000.

Is this functionality included right now? If not, I'd be happy to build it in and submit a pull request.

Cheers!

500 Error for proxy to https

I successfully proxied my requests to a standard server on port 80.

Config:

[
    {
        context: '/apiproxy',
        host: 'api.example.org',
        port: 80,
        https: false,
        changeOrigin: true,
        rewrite: {
          '^/apiproxy': '',
        }
    }
]

But when I changed the server to https on port 443, I get a 500 form the node server.
Config:

[
    {
        context: '/apiproxy',
        host: 'api.example.org',
        port: 443,
        https: true,
        changeOrigin: true,
        rewrite: {
          '^/apiproxy': '',
        }
    }
]

The response says: An error has occurred: {}

Did I find a bug or am I doing something wrong?

The request not go with system VPN

Currently, i try to use grunt-connect-proxy for some third party services, but still have a problem. As you know, facebook is blocked in china, so when i try to use this plugin, i need to do two layer proxies. For example, there is a search service in facebook called fb.com/search?XXX , i want to proxy localhost/fb/search?XX to this service, and i also setted a system VPN so that i can access facebook.
And i expect the proxy is like: localhost/fb/search?XX -> fb.com/search?XXX -> VPN to get the result. But actually the connect-proxy always access the network directly without go with the VPN. So my question is there a way i can do with this case? Thanks.

Websocket support

Hi, how could i proxy websocket between the browser and the backend?

Thanks for the tips!

Host header not properly set in proxied request

here is my config:

connect: {
      server: {
        options: {
          port: 8000,
          base: 'src',
          keepalive: true,
          middleware: function (connect, options) {
            var proxy = require('grunt-connect-proxy/lib/utils').proxyRequest;
            return [
              proxy,
              connect.static(options.base[0]),
              connect.directory(options.base[0])
              ];
          }
        },
        proxies: [{
          context: '/otherapi',
          host: 'www.other.com',
          port: 80,
          https: false,
          headers: {
            'host': 'www.other.com'
          },
          rewrite: {
            '^/otherapi': '/api'
          }
        }]
      }
    }
  });

Which works, and successfully proxies all XHR requests to http://localhost:8000/otherapi to http://www.other.com/api. However, without the headers option, the proxy doesn't work. The request is sent to the ip for www.other.com but the host header is still localhost:8000 and the api request fails. I had to add the extra host header to get it to work, which I don't think should be required.

Nice to provide array to options.context

Instead of:

      proxies: [
        {
          host: 'foobar.com',
          context: '/api/v1',
          changeOrigin: true
        },
        {
          host: 'foobar.com',
          context: '/acct',
          changeOrigin: true
        }
      ],

It would be nice to write:

      proxies: [
        {
          host: 'foobar.com',
          context: ['/api/v1', '/acct']
          changeOrigin: true
        }
      ],

Latest Angular Generators

Hi,

I setup a new project with the Yeoman Angular generator and tried to proxy some calls to the Rails API backend. However, it seems that things have changed with the latest grunt-contrib-* packages and while I followed the documentation nothing works for me.

Can anyone please try setting up the proxy with the latest Angular generators and see if they are facing any problems.

Thanks :)

Enabling proxies for "dist" target

Hello,

This may be a somewhat of a silly question, but I haven't been able to come up with the proper configuration to allow proxying for a dist target. I have an angular app based on yeoman's angular generators and would like to test some aspects of the dist target without deploying the entire application.

My understanding of Grunt is somewhat limited, but wanted to ask the if this was in fact possible without proceeding down a rabbit hole.

Many thanks.

connect task:

      dist: {
        options: {
          middleware: function(connect, options) {
            if (!Array.isArray(options.base)) {
              options.base = [options.base];
            }

            // Setup the proxy
            var middlewares = [require('grunt-connect-proxy/lib/utils').proxyRequest];

            // Serve static files.
            options.base.forEach(function(base) {
              middlewares.push(connect.static(base));
            });

            // Make directory browse-able.
            var directory = options.directory || options.base[options.base.length - 1];
            middlewares.push(connect.directory(directory));

            return middlewares;
          },
          open: false,
          base: [
            '<%= yeoman.dist %>'
          ]
        }
      }

actual grunt task

  grunt.registerTask('serve', function(target) {
    if (target === 'dist') {
      return grunt.task.run([
        'build',
        'configureProxies:dist',
        'connect:dist:keepalive'
      ]);
    }
...
}

Trying to load proxy fails

Hi,

I am trying to integrate your setup in this Gruntfile:

var proxySnippet = require('grunt-connect-proxy/lib/utils').proxyRequest;

module.exports = function(grunt) {
  var port = 8000,
      publicDir = './public',
      jsDir = publicDir + '/modules',
      lumbarFile = './lumbar.json',
      hostname = 'localhost';

  grunt.file.mkdir(publicDir);
  grunt.file.mkdir(jsDir);

  grunt.initConfig({
    // create a static webserver
    connect: {
      server: {
        options: {
          hostname: hostname,
          base: publicDir,
          port: port
        },
      proxies: [
                {
                    context: '/cortex',
                    host: '0.0.0.0',
                    port: 9292,
                    https: false,
                    changeOrigin: false
                }
       ],
        livereload: {
              options: {
                 middleware: function (connect, options) {
                   return [
                            proxySnippet
                        ];
               }
            }
        }
      }
    },
    lumbar: {
      // performs an initial build so when tests
      // and initial open are run, code is built
      init: {
        build: lumbarFile,
        output: jsDir
      },
      // a long running process that will watch
      // for updates, to include another long
      // running task such as "watch", set
      // background: true
      watch: {
        background: false,
        watch: lumbarFile,
        output: jsDir
      }
    },
    // allows files to be opened when the
    // Thorax Inspector Chrome extension
    // is installed
    thorax: {
      inspector: {
        background: true,
        editor: "subl",
        paths: {
          views: "./js/views",
          models: "./js/models",
          collections: "./js/collections",
          templates: "./templates"
        }
      }
    }
  });

  grunt.registerTask('open-browser', function() {
    var open = require('open');
    open('http://' + hostname + ':' + port);
  });

  grunt.loadTasks('tasks');
  grunt.loadNpmTasks('thorax-inspector');
  grunt.loadNpmTasks('grunt-connect-proxy');
  grunt.loadNpmTasks('lumbar');
  grunt.loadNpmTasks('grunt-contrib-connect');

  grunt.registerTask('default', [
    'thorax:inspector',
    'lumbar:init',
    'connect:server',
    'open-browser',
    'connect:livereload',
    'lumbar:watch'
  ]);
};

But I get the error:

Running "connect:livereload" (connect) task
Verifying property connect.livereload exists in config...ERROR
>> Unable to process task.
Warning: Required config property "connect.livereload" missing. Use --force to continue.

Any help would be great! Thanks!

Can't figure out how to remove all contexts

Hi again!

I am developing a single page app and I want any url within my app's domain name to be served from exactly the same script. Thus, while in development, I want any of those urls:

  http://localhost:3000
  http://localhost:3000/whatever
  http://localhost:3000/whatever/somemore

to be served from http://localhost:3000 and it is not clear to me how to do it from the README examples. I have tried in a lot of different ways with no luck so far. I would appreciate any help on this.

problem with self signed certificats

I have a self signed certificate on a https site I point the proxy to.
I get the following error:
Fatal error: Parse Error
Fatal error: socket hang up

my configuration is:

proxies: [{
        context: '/api', // the context of the data service
        host: 'my-https-api-site', // wherever the data service is running
        port: 443,
        https: true,
        xforward: true,

      }],
livereload: {
        options: {
          open: {target: 'http://localhost:9000'},
          base: [
        '.tmp',
        '<%= yeoman.app %>'
        ],

please help,
Shay

Cannot read property 'proxyWs'

Updating to 0.1.7 gives me the following error:

TypeError: Cannot read property 'proxyWs' of undefined
    at enableWebsocket (/.../grunt-connect-proxy/lib/utils.js:99:16)
    at Object.utils.proxyRequest [as handle] (/.../grunt-connect-proxy/lib/utils.js:109:5)
    at next (/.../grunt-contrib-connect/node_modules/connect/lib/proto.js:190:15)
    at Object.handle (/.../grunt-contrib-connect/node_modules/connect-livereload/index.js:84:5)
    at next (/.../grunt-contrib-connect/node_modules/connect/lib/proto.js:190:15)
    at Function.app.handle (/.../grunt-contrib-connect/node_modules/connect/lib/proto.js:198:3)
    at Server.app (/.../grunt-contrib-connect/node_modules/connect/lib/connect.js:65:37)
    at Server.EventEmitter.emit (events.js:98:17)
    at HTTPParser.parser.onIncoming (http.js:2108:12)
    at HTTPParser.parserOnHeadersComplete [as onHeadersComplete] (http.js:121:23)

The offending line is from lib/utils:

if (!server.proxyWs) {

Changing it to the following appears to resolve the issue:

if (server && !server.proxyWs) {

I do not know the full breadth of code for this project, so I don't know if perhaps my config is setup wrong for 0.1.7, but it at least worked fine for 0.1.6.

Reference issue #34.

Configure proxies to work behind a corporate proxy

When I'm out of the office, I use the following config;

proxies: [{
context: '/V2',
host: "services.odata.org",
changeOrigin: true
}]

And it works. In my office I have proxy, {host: "proxy.location.company.corp", port: 8080}.

I tried this:
proxies:
[
{
context: '/v2',
host: 'proxy.location.company.corp',
port: 8080, // proxy port
headers: {
Host: "services.odata.org"
},
changeOrigin: true
}
]

with no luck however.

How can I configure this to work when in the office.

Thank you

Proxying not working with vhost

First of all: You r awesome.

I am trying to proxy ajax calls from localhost:9000 to 'example.dev:80'.
Example.dev is a local apache instance.

proxies: [
{
context: '/api',
host: example.dev',
port: 80
}
],

From the apache log files I see that apache is always trying to load the document root (localhost).

should it be possible to make a post request to foo.dev running on apache2

I try to make a post request and all works fine, the route is accessed, but the $_POST in php stays empty

from angularJS
$http.post("/api", {"foo":"bar"})
.success(function(data, status, headers, config) {
$scope.data = data;
console.log(data);
}).error(function(data, status, headers, config) {
$scope.status = status;
});

$route3 = $r->post("/api",function() use($request){
$myarray = array('bar' => 'foo','foo' =>'bas'); // test to see if response can actually return something
$post = $request->request->all(); is parameterBag from Symfony
if (count($_POST) == 0) { // raw post array
throw new Exception("Error Processing ". print_r($_POST,true), 1);

}
return new JasonResponse($_POST);

0.1.11 caused fatal error: socket hang up

The latest update to 0.1.11 caused my existing proxy setup to fail with "fatal error: socket hang up".

My setup:

proxies: [
          {
            context: '/api',
            host: '...',
            port: 443,
            https: true,
            changeOrigin: true,
            xforward: false,
            rejectUnauthorized: false
          }
        ]

The error only occured when trying to use https.

Switching back to 0.1.10 resolved my issue.

Explodes on 204 response

Hi!

I came across a strangest thing. Whenever our API returns a 204 (No content) status typically as a result of DELETE our connect/connect-proxy stack explodes giving a meaningless error: "Fatal error: Can't render headers after they are sent to the client."

Could you please check if 204 status header in response works well for you?

Thanks and have a great day :)

Proxy broken?

I tried with a simple gruntfile but never succeed to make it works

/* global module */


module.exports = function(grunt) {

    grunt.initConfig({

        connect: {
            server: {
                options: {
                    hostname: 'localhost',
                    open: true,
                    port: 8080,
                    keepalive: true

                },
                proxies: [
                    {
                        context: '/api',
                        host: 'localhost',
                        port: 8001
                    }
                ]
            }
        }

    });


    grunt.loadNpmTasks('grunt-contrib-connect');
    grunt.loadNpmTasks('grunt-connect-proxy');

    grunt.registerTask('default', [
        'configureProxies:server',
        'connect:server'
    ]);

};

Opening localhost:8080/api I have a Cannot GET /api displayed even if I create a folder api in the folder served under my other server on 8001.

If I create a folder api under the folder of this Gruntfile I have no longer the error... but that's not what I expected.

Is it possible to use a wildcard in context?

Is it possible to use a wildcard in this context?

{
context: [
'/[wildcard]/all_docs'
],
host: '127.0.0.1',
port: grunt.config.get('connect.proxies.1.port'),
https: false,
changeOrigin: true,
xforward: false,
ws: true,
headers: {
"Access-Control-Allow-Origin": "
",
"Access-Control-Allow-Methods": "_",
},
rewrite: {
'^/_all_docs' : '^/_all_docs'
}
}

Changing headers

A possibility to change specific header would be nice. I ran into a problem where i had to remove the referer header to get a CORS request for dev running.

in utils.proxyRequest i added:

req.headers.referer = (!proxy.config.referer) ? '' : req.headers.referer;

and changed config in the gruntfile accrodingly. Would be nice to change headers more generaly. Or i there a better solution?

what do you think?

Server error when https option set to true

Hi. I'm having a little trouble setting up a proxy from http to https. If I understand the documentation, if I set the https option to true the proxy should use https. But when I do this I just get An error has occurred: {} and a 500 server error code.

Here's my setup:

        connect:
            # host your app folder with a proxy mapped to a live service
            app:
                options:
                    port: 3333
                    middleware: _getAppMiddleware # I set up a mount folder here
                proxies: [
                    context: "/mls"
                    host: "staging.mytargetsite.org.uk"

                    https: true # if I remove this line, it works ok. But over http
                    rewrite:
                        "^/mls": "/API"
                ]

So if I remove the https: true line it all works ok. But over http. This causes a redirect to the proper https site which screws up my call.

How do I get the proxy to use https? Am I doing something wrong?

Unable to download pdf files through the proxy

Hi everyone,

I am unable to download pdf files through the proxy served by an ordinary servlet at /myapp/pdfservlet/ on my tomcat server.
When I try without proxy, pdf files are correctly downloaded.

Here is my proxy configuration:

{
    context: '/', // the context of the data service
    host: localhost, // wherever the data service is running
    port: 8080, // the port that the data service is running on
    ws: true, // Proxy websocket
    rewrite: { '^/myapp/realtime/fallback':  '/myapp/realtime'},
        excludedFileTypes: ['pdf', 'jar', 'gz']
}

Here is the request/response given by Chrome:

Remote Address:127.0.0.1:9000
Request URL:http://localhost:9000/myapp/pdfservlet
Request Method:GET
Status Code:200 OK

Request Headers
Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Accept-Encoding:gzip,deflate,sdch
Accept-Language:fr-FR,fr;q=0.8,en-US;q=0.6,en;q=0.4,de;q=0.2,es;q=0.2
Connection:keep-alive
Host:localhost:9000
Referer:http://localhost:9000/myapp/jsp/foo.jsp
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.103 Safari/537.36

Response Headers
connection:close
content-disposition:filename="foo.pdf"
content-language:fr-FR
content-type:application/pdf;charset=UTF-8
date:Wed, 10 Sep 2014 17:36:13 GMT
server:Apache-Coyote/1.1
transfer-encoding:chunked

It also happens on .gz files.
It seems that the connection is closed before the end of the file because the pdf is just blank.

Am I missing something?

jit-grunt support

How can I use the configureProxies task with jit-grunt? I'm always getting:

jit-grunt: Plugin for the "configureProxies" task not found.
If you have installed the plugin already, please setting the static mapping.
See https://github.com/shootaroo/jit-grunt#static-mappings

Warning: Task "configureProxies:connect" not found. Use --force to continue.

Replacement for changeOrigin option?

The changeOrigin option was removed in 0.1.11 (worked fine in 0.1.10). Is there any replacement for this? How can i change the host header of the proxied request so that it matches the one from the original request? We need this functionality for our project to work properly.

BTW: Removing this option was not a minor change because it breaks existing functionalities which should not happen when increasing only the last digit of the version number. Instead, the 0.1.11 release should have been named 0.2.x because of this incompatible change.

302 Found/Temporary moved not proxied?

Backend responds with such a code but client receives 200.

The proxy configuration is:
proxy_api: {

            proxies: [{
                context: '/api',
                host: 'localhost',
                port: 9500
            }]
        }

Is there anything else I should do?

500 Error on Apache

Thanks much for your work. Just FYI, I've come across something that might be of interest to others.

I set things up as is shown in the example:

context: '/dev/logger/backend',
host: 'localhost',
port: 80,
https: 'false',
changeOrigin: 'true'

...however I kept getting 500 errors when requesting files like localhost:9000/dev/logger/backend. In the Apache log (I'm running Apache/PHP on the backend) I'd get entries like the following:

127.0.0.1 - - [15/May/2013:16:06:36 -0500] "\x16\x03\x01" 501 290 "-" "-"

I discovered that if I comment out the "https: 'false'," line, things work correctly.

Configuring proxy middleware removes connect.static middleware

Hi,

I was trying to setup my dev environment where I serve the static files (html, js, css) from local dir and proxy the REST requests to another server running on the different port. I was a bit confused how to use this, but if I configure how I saw in the documentation than it will remove the connect.static.

middleware: function (connect) {
  return [
    proxySnippet
  ];
}

So I had to do this ugly trick

middleware: function (connect) {
  return [
    connect.static(__dirname),
    proxySnippet
  ];
}

Do I misunderstand something?

Thx.

Proxy not catching requests?

I am having issues catching requests to api/..

        // The actual grunt server settings
        connect : {
            options : {

                port             : 9000,
                // Change this to '0.0.0.0' to access the server from outside.
                hostname         : '0.0.0.0',
                // hostname         : 'localhost',
                livereload       : 35729,
                useAvailablePort : true,

            },
            livereload : {
                options: {
                    open : true,
                    base : [
                        '.tmp',
                        '<%= yeoman.app %>'
                    ],

                    middleware: function (connect, options) {
                        if (!Array.isArray(options.base)) {
                            options.base = [options.base];
                        }

                        // Setup the proxy
                        var middlewares = [require('grunt-connect-proxy/lib/utils').proxyRequest];

                        // Serve static files.
                        options.base.forEach(function(base) {
                            middlewares.push(connect.static(base));
                        });

                        // Make directory browse-able.
                        var directory = options.directory || options.base[options.base.length - 1];
                        middlewares.push(connect.directory(directory));

                        return middlewares;
                    }

                },
            },
            test : {
                options: {
                    port : 9021,
                    base : [
                        '.tmp',
                        'test',
                        '<%= yeoman.app %>'
                    ]
                }
            },
            dist : {
                options : {
                    base : '<%= yeoman.dist %>'
                }
            },
            proxies : [{
                context      : '/api',
                host         : '10.0.4.121',
                port         : 8443,
                https        : true,
                changeOrigin : false,
                rewrite : {
                    '/api' : '/evidence/api/v2/ui/'
                }
            }]
        },

When I run grunt serve and try out some AJAX calls, they are still going to http://localhost:9000/api/etc. This is the raw header from Fiddler:

GET http://localhost:9000/api/ping/ HTTP/1.1
Host: localhost:9000
Connection: keep-alive
Accept: application/json, text/plain, */*
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.114 Safari/537.36
Referer: http://localhost:9000/
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-GB,en-US;q=0.8,en;q=0.6

Is it possible to proxy only xhr requests (or only non-xhr requests)?

I am developing an application which I want to behave both as a single-page app and as a conventional Rails (multipage) app.

Therefore, I want to proxy non-xhr requests to the Rails server, but all my ajax requests I want them to be handled by "connect". Does this make sense? Is it currently feasible with grunt-connect-proxy?

Can't get proxy working with a basic test odata service: ECONNREFUSED

I've been trying to get grunt-connect-proxy to proxy requests containing "/Northwind" at localhost:8080 to services.odata.org:80.

i.e. when a GET http://localhost:8080/Northwind/Northwind.svc/ occurs the proxy should do a GET http://services.odata.org:80/Northwind/Northwind.svc/.

However - I always get a ECONNREFUSED error with no further details. When I run grunt serve --verbose I can see that it looks like its proxying correctly as shown here:

Proxied request: /Northwind/Northwind.svc/$metadata -> http://services.odata.org:80/Northwind/Northwind.svc/$metadata
{
  "host": "services.odata.org",
  "connection": "keep-alive",
  "cache-control": "max-age=0",
  "accept": "application/xml",
  "accept-language": "en-US",
  "maxdataserviceversion": "3.0",
  "user-agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.64 Safari/537.31",
  "referer": "http://localhost:8080/odata.html",
  "accept-encoding": "gzip,deflate,sdch",
  "accept-charset": "ISO-8859-1,utf-8;q=0.7,*;q=0.3"
}

The Gruntfile.js is here: https://gist.github.com/js1972/8593226

I execute the "grunt serve --verbose" task.

I've been crawling the net for answers and someone posted something about requiring CORS headers which I think is bizarre as the whole reason for proxying here is to get around that. I've added them as a middleware as you can see in the Gruntfile.js. with or without them it makes no difference and I get the same error.

btw. The Northwind service is up and running fine and I can paste the url's into by browser and they reply with xml data.

From what I can see and the examples I've found it looks like I have the config right... Could it be an issue with grunt-connect-proxy or have I done something really stupid?

Any help or pointers would be greatly appreciated... ;-)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.