Grunt HTTP Request Task

raw JSON →
2.3.3 verified Thu Apr 23 auth: no javascript abandoned

grunt-http is a Grunt plugin that facilitates sending HTTP requests and handling their responses within a Grunt build workflow. It acts as a wrapper around the popular, but now deprecated, `request` module. The current stable version is 2.3.3, but the package has not seen updates since 2018, indicating it is no longer actively maintained. Its core functionality allows developers to configure various HTTP methods, headers, query parameters, and request bodies, along with options to save responses to files or process them via callbacks. Unlike modern fetch APIs, it integrates directly into the Grunt task runner, making it suitable for older build systems still relying on Grunt for network operations. Its primary differentiator is its deep integration with Grunt's configuration and file handling system, inheriting the `request` module's extensive options for HTTP client behavior.

error Warning: Task "http" not found. Use --force to continue.
cause The `grunt-http` plugin has not been correctly loaded in the Gruntfile.js.
fix
Add grunt.loadNpmTasks('grunt-http'); to your Gruntfile.js after grunt.initConfig().
error TypeError: Request path contains unescaped characters
cause The `url` or `uri` option contains special characters (like spaces) that are not URL-encoded.
fix
Ensure that all components of the URL that are not part of the path structure (e.g., query parameters values) are properly URL-encoded using encodeURIComponent() if constructed dynamically.
error Error: options.uri is a required argument
cause The `url` or `uri` option is missing or empty in your `http` task configuration.
fix
Provide a valid url or uri string within the options object for your http task target. For example: options: { url: 'http://example.com' }.
error Warning: 'Request' library error: connect ECONNREFUSED 127.0.0.1:80
cause The HTTP request failed to connect to the specified server, often due to the server not running, incorrect URL, or firewall issues.
fix
Verify the url option is correct, ensure the target server is running and accessible from the machine running Grunt, and check any local firewall configurations that might block the connection.
breaking The underlying `request` library, which grunt-http heavily relies upon, has been officially deprecated since February 2020. This means it no longer receives updates, including security fixes or new features, posing potential security risks and compatibility issues with modern Node.js environments.
fix Consider migrating to a modern, actively maintained HTTP client like `axios`, `node-fetch`, or Node.js's built-in `http`/`https` modules, and replace `grunt-http` with a custom Grunt task or a different build tool if HTTP requests are critical to your build process.
gotcha grunt-http supports Grunt versions `>=0.4.1` and Node.js versions `>=0.8.0`. These are very old requirements, and running this plugin with recent versions of Grunt or Node.js may lead to unexpected behavior or incompatibilities, especially given the `request` library's deprecation.
fix Ensure your project's Grunt and Node.js versions match the plugin's compatibility range if you must continue using it. Ideally, update your build system away from such outdated dependencies.
gotcha When using `multipart/form-data`, the `form-data` package is an optional dependency that must be installed separately. Failing to install it will result in errors when attempting multipart requests.
fix Run `npm install form-data --save-dev` if you intend to send `multipart/form-data` requests.
deprecated The `request` module (and by extension `grunt-http`) handles SSL certificate validation with the `strictSSL` option. Relying on older or deprecated HTTP clients can introduce vulnerabilities if not properly configured or if the underlying client has known security flaws that are no longer patched.
fix If working with HTTPS, always keep `strictSSL` set to `true` (its default). For self-signed certificates in development, use `rejectUnauthorized: false` with caution, or configure an appropriate `agent` with your custom certificate authority if necessary.
npm install grunt-http
yarn add grunt-http
pnpm add grunt-http

This Gruntfile example demonstrates how to configure and run both GET and POST HTTP requests using grunt-http. It fetches data from a public API, logs the response, and optionally saves it to a file, then sends a POST request with JSON data and logs the outcome.

module.exports = function(grunt) {
  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    http: {
      getData: {
        options: {
          url: 'https://jsonplaceholder.typicode.com/posts/1',
          method: 'GET',
          headers: {
            'User-Agent': 'Grunt-HTTP-Client'
          },
          callback: function(error, response, body) {
            if (error) {
              grunt.log.error('HTTP Error:', error.message);
            } else if (response.statusCode >= 400) {
              grunt.log.warn('API responded with status %d: %s', response.statusCode, body);
            } else {
              grunt.log.ok('Fetched data successfully:\n', body.substring(0, 100) + '...');
            }
          }
        },
        // Optionally save the response to a file
        dest: 'dist/post-data.json'
      },
      postData: {
        options: {
          url: 'https://jsonplaceholder.typicode.com/posts',
          method: 'POST',
          json: {
            title: 'foo',
            body: 'bar',
            userId: 1
          },
          callback: function(error, response, body) {
            if (!error && response.statusCode === 201) {
              grunt.log.ok('Posted data successfully:', JSON.stringify(body));
            } else if (error) {
               grunt.log.error('POST Error:', error.message);
            } else {
              grunt.log.warn('POST failed with status %d: %s', response.statusCode, JSON.stringify(body));
            }
          }
        }
      }
    }
  });

  grunt.loadNpmTasks('grunt-http');

  grunt.registerTask('default', ['http:getData', 'http:postData']);
};