Skip to content

Instantly share code, notes, and snippets.

@j3lte
Last active December 22, 2015 11:09
Show Gist options
  • Save j3lte/6463805 to your computer and use it in GitHub Desktop.
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/
// 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
@j3lte
Copy link
Author

j3lte commented Mar 20, 2014

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment