Simplifies node HTTP request making.

Overview

Requestify - Simplifies node HTTP request making. Build Status

Requestify is a super easy to use and extendable HTTP client for nodeJS + it supports cache (-:.

Installation

npm install requestify  

How to use?

Requestify is extremely easy to use and always return a promise (using the amazing Q module)...

Simply require the module and start requesting:

var requestify = require('requestify'); 

GET Request:

requestify.get('http://example.com').then(function(response) {
	// Get the response body
	response.getBody();
});

POST Request in JSON:

requestify.post('http://example.com', {
		hello: 'world'
	})
	.then(function(response) {
		// Get the response body (JSON parsed or jQuery object for XMLs)
		response.getBody();
		
		// Get the raw response body
		response.body;
	});

Configuration methods

requestify.setEncoding(encoding)

Sets Requestify's encoding. Requestify will use this encoding to decode the responses. Defaults to utf8.

requestify.setEncoding('utf8'); // utf8 is set by default anyway.

requestify.cacheTransporter(cacheTransporter)

Sets the cache transporter for Requestify's use. Requestify will use this transporter for caching the desired HTTP responses. For using one of Requestify's core transporter use the core transporters object (coreCacheTransporters). PLEASE NOTE: the inMemory() transporter is set by default.

For example:

var coreCacheTransporters = requestify.coreCacheTransporters;
requestify.cacheTransporter(coreCacheTransporters.inMemory()); // set simple in-memory caching (set by default)
requestify.cacheTransporter(coreCacheTransporters.redis(myRedisInstance)); // Set the core Redis cache transporter, or
requestify.cacheTransporter(coreCacheTransporters.mongo(myMongooseInstance)); // set the core Mongo cache transporter

You can implement your own cache transporters (@see docs below)

requestify.redis(redisInstance) - @depercated

Sets Redis client instance. Requestify will use that instance for caching responses. Please note, Requestify will NOT cache anything by default and caching is allowed only for GET requests (see @cache options for further info).

PLEASE NOTE, this method is only a shorthand for using requestify.cacheTransporter(coreCacheTransporters.redis(myRedisInstance));

var redis = require('redis');

requestify.redis(redis.createClient());

API Reference

options

method {string}

HTTP method to use, can be any valid HTTP method (e.g. POST, GET, DELETE, HEAD, PUT, etc.).

body {object|string}

Can be either an object (key, val) or a string, will be formatted depending on the dataType property and served via request body.

params {object}

Object of key-value params, will be encoded to url encoded string and added as the request query string.

headers {object}

(key, value) object of headers (some headers like content-length are set by default)

cookies {object}

(key, value) object of cookies to encode and serve via the request header.

auth {{ username: string, password: string }}

Adds Basic authentication header with given username and password

dataType {string}

Determines the request data type (json|form-url-encoded), this option will encode the request body according to the given dataType and will add the appropriate header (defaults to json).

If null will be given, the body will be served as string.

timeout {number}

Set a timeout (in milliseconds) for the request.

redirect {boolean}

Determines if should continue with redirects

cache {{ cache: boolean, expires: number }}

Requistify has built-in Redis based caching mechanism. For using this feature, set the cache property to true using the following object:

requestify.get('http://examples.com/api/foo', {
    cache: {
    	cache: true, // Will set caching to true for this request.
    	expires: 3600 // Time for cache to expire in milliseconds
    }
});

Caching will always be set to false by default.

requestify.request(url, options)

Executes a custom request according to options object

requestify.request('https://example.com/api/foo', {
	method: 'POST',
	body: {
		foo: 'bar'
		bar: 'foo'
	},
	headers: {
		'X-Forwarded-By': 'me'
	},
	cookies: {
		mySession: 'some cookie value'
	},
	auth: {
		username: 'foo',
		password: 'bar'
	},
	dataType: 'json'		
})
.then(function(response) {
	// get the response body
	response.getBody();

   	// get the response headers
 	response.getHeaders();

 	// get specific response header
 	response.getHeader('Accept');
 
 	// get the code
 	response.getCode();
	
	// get the raw response body
	response.body;
});

requestify.get(url, options)

Executes a GET method request

requestify.get('http://example.com').then(function(response) {
	// Get the response body
	response.getBody();
});

requestify.post(url, data, options)

Executes a POST method request

requestify.post('http://example.com', {
		hello: 'world'
})
.then(function(response) {
	// Get the response body
	response.getBody();
});

requestify.put(url, data, options)

Executes a PUT method request

requestify.put('http://example.com', 'some-file-content').then(function(response) {
	// Get the response body
	response.getBody();
});

requestify.delete(url, options)

Executes a DELETE method request

requestify.delete('http://example.com').then(function(response) {
	// Get the response body
	response.getBody();
});

requestify.head(url, options)

Executes a HEAD method request

requestify.head('http://example.com').then(function(response) {
	// Get the response code
	response.getCode();
});

Handling Errors

While the .then() callback is used for handling succesful responses, the .fail() callback is used for handling errors.

requestify.get('http://example.com')
	.then(function(response) {
		response.getCode(); // Some code between 200-299
	})
	.fail(function(response) {
		response.getCode(); // Some error code such as, for example, 404
	});

Custom Cache Transporters

Using Requestify, you can implement your own cache transporters for using currently unsupported stores. To implement your own store, all you have to do is implement Requestify's cache transporter interface. For example, you can see the core Redis transporter (./cache-transporters). Below is the interface specs to implement:

get(url: string, callback: function)

Returns the response according to the given URL from your cache store and call the given callback with the data.

set(url: string, response: {{ code: number, headers: object, body: string, created: timestamp }}, callback: function)

Store the given response by the given URL (key), please make sure to store the response object exactly in the same way you've got it.

purge(url: string, callback: function)

Purge the response according to the given URL (key) from your cache store.

Running Tests

To run the test suite first install the development dependencies:

$ npm install	

Then run the tests:

$ npm test

License

The MIT License (MIT)

Copyright (c) 2013 Ran Mizrahi <[email protected]>

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Comments
  • Error thrown in NodeJs 0.12.0

    Error thrown in NodeJs 0.12.0

    node_modules/requestify/node_modules/jquery/node_modules/jsdom/lib/jsdom/level1/core.js:418
    set nodeName() { throw new core.DOMException();},
                 ^
    SyntaxError: Unexpected token )
    

    JsDOM actually fixed this issue a while back, and jQuery no longer uses JsDOM. Probably need to upgrade the jQuery version to run in v0.12 of Node.

    opened by rgeraldporter 8
  • Incorrect content length when body contains unicode characters

    Incorrect content length when body contains unicode characters

    Because Request.prototype.getContentLength uses string.length, requestify breaks on unicode bodies. It looks like this is fixed in the 0.2.0 branch, which is not published to npm. Any timetable on that?

    opened by osuushi 6
  • Trying to send POST payload

    Trying to send POST payload

    I'm trying to send off a payload, but it's not working.

    Sending script:

    requestify.post('http://localhost/rest.php',  {test:'123',foo:'bar'})
    .then(function(response) {
        // get the response body
        console.log('got response');
    
        response.getBody();
    
     res.send(response.body);
    
    
    });
    

    Here's the PHP script that accepts:

    <?php
    
    
    print_r($_POST);
    

    and returns an empty

    Array ( )
    

    I get

    verbose: Attempted to retry bodyParse as JSON.  But no luck. Error: invalid json, empty body
    

    Any ideas? I hate to go back to using raw express http.request

    opened by drj-io 4
  •     rejectUnauthorized: false,

    rejectUnauthorized: false,

    I had to had to add this express option manually to the https.request in your module in order to get a request working to HTTPS. I didn't see a way to add it through the options.

    opened by drj-io 4
  • cache never expries

    cache never expries

    This line if (!data || (data.created + request.cache.expires > new Date().getTime())) {

    should be change if (!data || (data.created + request.cache.expires < new Date().getTime())) {

    In Requestify.js, Line : 155

    opened by jinweilin 3
  • mention how to handle errors in readme

    mention how to handle errors in readme

    I am using this library to make requests and had to go trawling through the code to work out what was happening when a http error happened. Could it be added to the readme like so:

    Handling Errors

    to handle errors, pass a second function to the then call:

    requestify.post(url, data).then(successFunction, errorFunction);
    

    Might save people some time trying to work it out.

    opened by benkaiser 3
  • No Way To Catch

    No Way To Catch "404 Page Not Found"?

    Here is an example program that will make a GET request to a URL that responds with error code 404.

    var url = 'http://www.google.com/bad/path/';
    var requestify = require('requestify');
    
    // Keep process alive while waiting for callbacks
    setInterval(function() {}, 1000);
    
    console.log('Getting ' + url);
    requestify.get(url).then(function(response) {
        console.log('This text will never be printed.');
    });
    

    Requestify doesn't seem to call the response callback, and the program hangs indefinitely!

    This seems so rudimentary, surely I'm doing something wrong?

    opened by Joncom 2
  • jQuery doesn't work on node 0.10.x

    jQuery doesn't work on node 0.10.x

    I've included a workaround for coolaj86/node-jquery#52 -- use jquery-loader instead of the package maintained by @coolaj86 (node-jquery). See more here: coolaj86/node-jquery#59 jquery-loader serves jQuery 1.10.1 by default which should not have an impact on how it is used in this project.

    opened by mrm007 2
  • Cannot set property 'method' of undefined

    Cannot set property 'method' of undefined

    I tried this: requestify.get("http://google.com").then(function(response) {console.dir(123);});

    And got this: /home/erelsgl/git/aimnegochat/node_modules/requestify/lib/Requestify.js:238 options.method = name.toUpperCase(); ^ TypeError: Cannot set property 'method' of undefined at Object.api.(anonymous function) as get

    opened by erelsgl 2
  • data does not arrive properly in req.body when sending data through requestify

    data does not arrive properly in req.body when sending data through requestify

    Hi Guys,

    am not able to send data properly to other server using requestify. can you guys figure it out whats wrong with below data.

    POST /1mmh0v8 HTTP/1.1 Host: requestb.in Content-Type: application/json app_user_token: 301e415579646e Cache-Control: no-cache

    {"data":[{"user_id":"1","username":"prav","firstname":"​prav","lastname":"​chel","exit":true,"is_delete":false},{"user_id":"2","username":"hubertp","firstname":"​hubert","lastname":"pin","exit":true,"is_delete":false}]}

    am not able to receive posted data through requestify . the other end data that what i am receiving is

    {"data":[{"user_id":"1","username":"prav","firstname":"​prav","lastname":"​chel","exit":true,"is_delete":false},{"user_id":"2","username":"hubertp","firstname":"​hubert","lastname":"pin","exit":t

    i cant able to figure it out. i debugged and checked each and everything still i cant able to figure it out

    opened by vasuvanka 1
  • Allow basic auth password to be null

    Allow basic auth password to be null

    Providing basic auth credentials with an empty password causes the auth to be set to null, which is not correct. e.g.

    {
      "username": "kevin",
      "password": ""
    }
    

    Basic auth is now set to null only if both the username and password are not provided or empty

    opened by kevgathuku 1
  • Wrong status sent on timeout

    Wrong status sent on timeout

    This code sends a 405 on timeout:

    timeout = setTimeout(function() {
      httpRequest.abort();
      defer.reject(new Response(405, {}, 'timeout exceeded'));
    }, request.timeout);
    

    405 is "Method Not Allowed". Pretty sure this is supposed to be 504 "Gateway Timeout"

    opened by osuushi 0
  • Add withCredentials flag for global fetch

    Add withCredentials flag for global fetch

    Supporting CORS, fixing issue when using session id not on the same domain, on the global fetch there is withCredentials flag, if its true it will set the credentials to "include" otherwise to same-origin.

    opened by ofirattia 0
  • not checked

    not checked

    Not checked status on stream

    var STREAMER_ID = 'lirik'; var checkStreamUrl = 'https://api.twitch.tv/kraken/streams/'+STREAMER_ID+'?client_id=ott641ae4i3mq3vz86vkwm9qzj3wobs'; function checkStream() { requestify.get(checkStreamUrl).then(function(response) {
    if(response.getBody().stream === null) { isStreamOnline = false; console.log("Status: Offline"); } else { if(typeof(isStreamOnline) !== 'undefined' && !isStreamOnline) { console.log("Status: Online"); } isStreamOnline = true; }
    }); }

    opened by S1ROZHA 0
  • Can't asign content-type on POST

    Can't asign content-type on POST

    Hi guys i'm trying to get a token from a service but it said's "error":"invalid_request","error_description":"Missing grant type i was searching about this error and the solution is changing the content-type to "application/x-www-form-urlencoded" cause it can be sended by JSON. but it doesn't work, my code is this

    ` var json = JSON.parse(JSON.stringify(jsonResp))

    var body = decryptBody(req.body); body = body.replace(/\0/g, '') body = JSON.parse(body) var auth = {grant_type:"password", username: "pass" , password: "usr" } if(!isValidProtocol(body)){ //console.log(body) json.error = true, json.desc = 'invalid protocol' res.statusCode = 202; res.json(encryptBody(json)); }

    requestify.request( "http://localhost:7070" + '/oauth/token',{ method: "POST", headers: {'Content-Type': 'application/x-www-form-urlencoded'}, dataType: 'form-url-encoded', auth: auth }) .then(function(response) { json.data = response.getBody(); res.json(encryptBody(json)); }).catch(function(err){ console.log('ERROR:') console.log(err) //console.log(body.data) console.log(auth) json.error = true, json.desc = 'invalid login params' res.statusCode = 202; res.json(encryptBody(json)); });`

    and the result

    ERROR: Response { code: 400, headers: { 'x-content-type-options': 'nosniff', 'x-xss-protection': '1; mode=block', 'cache-control': 'no-cache, no-store, max-age=0, must-revalidate', pragma: 'no-cache', expires: '0', 'x-frame-options': 'DENY', 'content-type': 'application/json;charset=UTF-8', 'transfer-encoding': 'chunked', date: 'Tue, 20 Jun 2017 19:31:43 GMT', connection: 'close' }, body: '{"error":"invalid_request","error_description":"Missing grant type"}' } Waitng for the answer, THANK YOU..

    opened by megamauricio009 0
  • Like it but Needs some polish

    Like it but Needs some polish

    I really like requestify. But it needs from polish to truly be that thing I keep seeing all over the internet that you say you want it to be.

    For instance, IMO, it is a design flaw/ short sighting that you can not do a simply. var options = { header: { ... blabla ... }, body { ... blablaagain ... } }; requestify.post(url, options);

    opened by sslyle 0
Owner
Ran Mizrahi
Author of Bit; Software Engineer.
Ran Mizrahi
🏊🏾 Simplified HTTP request client.

Deprecated! As of Feb 11th 2020, request is fully deprecated. No new changes are expected to land. In fact, none have landed for some time. For more i

request 25.6k Jan 4, 2023
Node.js web server framework for Http/1.1 or Http/2

Node.js web server framework for Http/1.1 or Http/2 Description: This is http framework, you can use it to create Http/1.1 or Http/2 service。 Now let'

Jeremy Yu 10 Mar 24, 2022
A tiny Node.js module for retrieving a request's Details (ip,os,browser)

request-details A tiny Node.js module for retrieving a request's Details (ip,os,browser) ⌨️ Installation npm install request-details ⚙️ Usage const Re

sajjad MrX 14 Aug 20, 2022
✍️ Forever Diary Testimonial Request Script

✍️ Forever Diary Testimonial Request Script ❓ Why? For people like Nauty who have too many people to send Testimonial Requests to :') ??️ How to use?

Jonathan Samuel J 2 Jan 26, 2022
A jQuery plugin for make your ajax request's error and success messages auto handled.

sweetAjax A jQuery plugin for make your ajax request's error and success messages auto handled. Installation sweetAjax plugin has built on jQuery-ui w

Eren Sertkaya 2 May 17, 2022
Promise based HTTP client for the browser and node.js

axios Promise based HTTP client for the browser and node.js New axios docs website: click here Table of Contents Features Browser Support Installing E

axios 98k Dec 31, 2022
Ajax for Node.js and browsers (JS HTTP client)

superagent Small progressive client-side HTTP request library, and Node.js module with the same API, supporting many high-level HTTP client features T

Sloth 16.2k Jan 1, 2023
A full-featured http proxy for node.js

node-http-proxy node-http-proxy is an HTTP programmable proxying library that supports websockets. It is suitable for implementing components such as

http ... PARTY! 13.1k Jan 3, 2023
HTTP server mocking and expectations library for Node.js

Nock HTTP server mocking and expectations library for Node.js Nock can be used to test modules that perform HTTP requests in isolation. For instance,

Nock 11.9k Jan 3, 2023
Full-featured, middleware-oriented, programmatic HTTP and WebSocket proxy for node.js

rocky A multipurpose, full-featured, middleware-oriented and hackable HTTP/S and WebSocket proxy with powerful built-in features such as versatile rou

Tom 370 Nov 24, 2022
Run HTTP over UDP with Node.js

nodejs-httpp - Run HTTP over UDP based transport and Bring Web in Peer or P2P styles main js modules: udt.js, httpp.js, udts.js and httpps.js, that's

AppNet.Link 142 Aug 2, 2022
Very very very powerful, extensible http client for both node.js and browser.

ES-Fetch-API 中文 | English Very very very powerful, extensible http client for both node.js and browser. Why should you use ES-Fetch API? Still using a

null 17 Dec 12, 2022
A serious cat corporation. (v03)(A game i'm making)

Introduction | Introdução This project was initially made to teach a friend of mine, from the basics of HTML to the advanced stuff of JS in a fun way.

Drayan Silva Magalhães 2 Sep 26, 2022
make streaming http requests

hyperquest treat http requests as a streaming transport The hyperquest api is a subset of request. This module works in the browser with browserify. r

James Halliday 711 Sep 8, 2022
HTTP Client Utilities

@hapi/wreck HTTP client utilities. wreck is part of the hapi ecosystem and was designed to work seamlessly with the hapi web framework and its other c

hapi.js 383 Nov 1, 2022
Wrap native HTTP requests with RFC compliant cache support

cacheable-request Wrap native HTTP requests with RFC compliant cache support RFC 7234 compliant HTTP caching for native Node.js HTTP/HTTPS requests. C

Luke Childs 259 Dec 20, 2022
Global HTTP/HTTPS proxy agent configurable using environment variables.

global-agent Global HTTP/HTTPS proxy configurable using environment variables. Usage Setup proxy using global-agent/bootstrap Setup proxy using bootst

Gajus Kuizinas 267 Dec 20, 2022
An HTTP Web Server for Chrome (chrome.sockets API)

An HTTP Web Server for Chrome (chrome.sockets API)

Kyle Graehl 1.2k Dec 31, 2022
HTTP Client for Visual Studio Code to POST JSON, XML, image, ... files to REST APIs

friflo POST Goal Main goal of this extension is storing all HTTP request & response data automatically as files in a VSCode workspace. This ensures th

Ullrich Praetz 2 Nov 18, 2021