Last active
December 22, 2015 11:09
-
-
Save j3lte/6463805 to your computer and use it in GitHub Desktop.
Grunt connect proxy JSON requests. Proposed solution for a problem I describe at: http://jeltelagendijk.nl/2013/09/grunt-connect-json-api-cross-domain/
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Add this at the top of Gruntfile.js: | |
var request = require('request'); | |
module.exports = function(grunt) { | |
grunt.initConfig({ | |
// ......... | |
// other grunt tasks | |
// ......... | |
// This is in your initConfig, add middleware to your grunt | |
connect: { | |
server: { | |
options: { | |
hostname:'*', | |
port: 9001, | |
base: 'dist', | |
/* | |
Custom middleware to make sure JSON requests are working! | |
*/ | |
middleware : function(connect, options) { | |
return [ | |
function(req,res,next) { | |
if (req.url.substring(0,5) == '/api/'){ | |
request('http://www.domain.com'+req.url, function (err, response, body) { | |
if (!err && response.statusCode == 200) { | |
res.end(body); | |
} | |
}); | |
} else { | |
return next(); | |
} | |
}, | |
connect.static(require('path').resolve(options.base)) | |
]; | |
} | |
} | |
} | |
} | |
// ......... | |
// other grunt tasks | |
// ......... | |
} | |
} | |
grunt.registerTask('dev', ['default','connect','watch:development']); | |
// run it using: grunt dev | |
// This will watch your files, start the connect-server and run various commands that are defined in the 'default' task |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
request is used to tunnel these api calls. Make sure request is added to package.json, then run
npm install
, this will make sure the package is installed. Also, at the top of your gruntfile, add this:var request = require('request');
That should do the trick