Much of this post is adapted from the grunt-connect-proxy documentation for my project's Yeoman-created Grunt.js.
Tools used:
- yo (Yeoman) 1.0.7-pre.2
- generator-angular 0.7.1
- grunt-cli v0.1.11
- grunt v0.4.2
- grunt-connect-proxy 0.1.7
I started with a working Angular webapp with Yeoman and friends, so check out Yeoman and generator-angular to get up to speed.
- Install grunt-connect-proxy in the root of your project folder. The
--save-dev
parameter tells NPM to add grunt-connect-proxy as a devDependency to your project's package.json.
npm install grunt-connect-proxy --save-dev
NOTE: The grunt-connect-proxy documentation states that you can enable it by adding the following line to your Gruntfile.js:grunt.loadNpmTasks('grunt-connect-proxy');
When I added it, Grunt registered the task twice and while this didn't appear to cause any problems, this is the reason that I leave it out of my Gruntfile.js. - Add a
proxies
config to yourconnect
config. I added it just beforelivereload
because we'll be modifying that config in the next step.// The actual grunt server settings connect: { options: { // content removed for brevity }, proxies: [{ context: '/data-service-path', // 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 }], livereload: { // content removed for brevity }, test: {
Check out the grunt-connect-proxy documentation for details on proxy configuration. - Add the grunt-connect-proxy
proxyRequest
function tomiddleware
inconnect.livereload.options
. This causes all requests to the Grunt server for the path of the configuredcontext
to be proxied; I'll provide some examples at the end of the post on how URLs are mapped by default. Here's what we end up with:// The actual grunt server settings connect: { options: { // content removed for brevity }, proxies: [{ context: '/data-service-path', // 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 }], livereload: { options: { open: true, base: [ '.tmp', '<%= yeoman.app %>' ], middleware: function (connect, options) { var middlewares = []; if (!Array.isArray(options.base)) { options.base = [options.base]; } // Setup the proxy middlewares.push(require('grunt-connect-proxy/lib/utils').proxyRequest); // Serve static files options.base.forEach(function(base) { middlewares.push(connect.static(base)); }); return middlewares; } } },
This is different from the example given in the grunt-connect-proxy documentation in that my version doesn't make anything browseable. - Add the
configureProxy
task to the Gruntserve
task. Here's what myserve
task ends up as:grunt.registerTask('serve', function (target) { if (target === 'dist') { return grunt.task.run(['build', 'connect:dist:keepalive']); } grunt.task.run([ 'clean:server', 'bower-install', 'concurrent:server', 'autoprefixer', 'configureProxies:server', // added just before connect 'connect:livereload', 'watch' ]); });
- Start up the Grunt server with
grunt serve
and you should seeRunning "configureProxies:server" (configureProxies) task Proxy created for: /data-service-path to localhost:8080
in the console.
Here are some example proxied URLs:
Grunt server | Backend server |
---|---|
http://127.0.0.1:9000/data-service-path | http://127.0.0.1:8080/data-service-path |
http://127.0.0.1:9000/data-service-path/foo/1 | http://127.0.0.1:8080/data-service-path/foo/1 |
For an Angular resource whose endpoint is over the proxy then, the proxy
context
must be used in the resource URL, something like this:
angular.module('myServices', ['ngResource']) .factory('Foo', ['$resource', function($resource) { return $resource('/data-service-path/foo/:id', {id: '@id'}); }]);To use a different path on the Grunt and backend servers, use the
rewrite
config; for example:
// The actual grunt server settings connect: { options: { // content removed for brevity }, proxies: [{ context: '/api', // the path your application uses host: 'localhost', // wherever the data service is running port: 8080, // the port that the data service is running on rewrite: { // the key '^/api' is a regex for the path to be rewritten // the value is the context of the data service '^/api': '/data-service-path' } }], livereload: { // content removed for brevity }, test: {Example URLs:
Grunt server | Backend server |
---|---|
http://127.0.0.1:9000/api | http://127.0.0.1:8080/data-service-path |
http://127.0.0.1:9000/api/foo/1 | http://127.0.0.1:8080/data-service-path/foo/1 |
Then our example resource code becomes:
angular.module('myServices', ['ngResource']) .factory('Foo', ['$resource', function($resource) { return $resource('/api/foo/:id', {id: '@id'}); }]);
Thanks for the helpful configuration walkthrough. After trying to read through the official docs for grunt-connect-proxy, your post was what finally made it all make sense. :)
ReplyDeleteAfter following the walkthrough I do have grunt telling me that the proxy is working. Upon running grunt serve I see the message:
ReplyDeleteRunning "configureProxies:server" (configureProxies) task
Proxy created for: /api to localhost:8080
However when I try to make a call using either $http or $resource I can see through the network and console that the call is still going to localhost:9000 which is where my node server is running the angular app. This is a gist of my gruntfile. Any input would be much appreciated.
https://gist.github.com/JohnBueno/7d48027f739cc91e0b79
@John - your proxies config is inside connect.server, but in my Gruntfile it's a child of connect, at the same level as livereload.
ReplyDeleteThe post incorrectly states that proxies should be added to connect.server, but I'll fix that shortly.
Thank you for this! Great details on what to put where... finally got everything working on my end. Cheers
ReplyDeleteThank you, this set me on the right path!
ReplyDeleteWith current versions of things (I guess this is due to updates on generator-angular, which for me is 0.11.1), step #3 gets slightly simpler since the middleware function already returns an array, you just have to add
require('grunt-connect-proxy/lib/utils').proxyRequest,
right after the lines "middleware: function (connect) { return [ ".
I also discovered what I think is a simpler way of doing what you do above, since this commit (version 0.7.1 of grunt-contrib-connect) you get the existing middlewares as a third parameter so you can just inject the proxy requester as the first element of the arrary - I haven't tested, but I think something like this should work:
https://gist.github.com/skagedal/9c4bcee9968e7242788d
This was a great and helpful post, thanks!
ReplyDeleteThis was a great post, thanks!
ReplyDeleteTHANK YOU SO MUCH!!!!!!!!!!!!!
ReplyDeleteI follow the instructions above, very similar is my configuration but when I do the "grunt serve" doesn't show that the proxy is created and the server start well. The proxy configurations do a rewrite of the port, nothing else but the proxy is never created. I wonder is have a bad configuration or something is missing.
ReplyDeleteInstallation detail:
npm --version -> 1.4.28
grunt --version -> v0.4.5
grunt-connect-proxy@0.2.0