Home

Awesome

then-request

A request library that returns promises and supports both browsers and node.js

Build Status Dependency Status NPM version

<a target='_blank' rel='nofollow' href='https://app.codesponsor.io/link/gg9sZwctSLxyov1sJwW6pfyS/then/then-request'> <img alt='Sponsor' width='888' height='68' src='https://app.codesponsor.io/embed/gg9sZwctSLxyov1sJwW6pfyS/then/then-request.svg' /> </a>

Installation

npm install then-request

Usage

request(method, url, options, callback?)

The following examples all work on both client and server.

var request = require('then-request');

request('GET', 'http://example.com').done(function (res) {
  console.log(res.getBody());
});

request('POST', 'http://example.com/json-api', {json: {some: 'values'}}).getBody('utf8').then(JSON.parse).done(function (res) {
  console.log(res);
});

var FormData = request.FormData;
var data = new FormData();

data.append('some', 'values');

request('POST', 'http://example.com/form-api', {form: data}).done(function (res) {
  console.log(res.getBody());
});

Or with ES6

import request, {FormData} from 'then-request';

request('GET', 'http://example.com').done((res) => {
  console.log(res.getBody());
});

request('POST', 'http://example.com/json-api', {json: {some: 'values'}}).getBody('utf8').then(JSON.parse).done((res) => {
  console.log(res);
});

var FormData = request.FormData;
var data = new FormData();

data.append('some', 'values');

request('POST', 'http://example.com/form-api', {form: data}).done((res) => {
  console.log(res.getBody());
});

Method:

An HTTP method (e.g. GET, POST, PUT, DELETE or HEAD). It is not case sensitive.

URL:

A url as a string (e.g. http://example.com). Relative URLs are allowed in the browser.

Options:

Returns:

A Promise is returned that eventually resolves to the Response. The resulting Promise also has an additional .getBody(encoding?) method that is equivallent to calling .then(function (res) { return res.getBody(encoding?); }).

Response

Note that even for status codes that represent an error, the promise will be resolved as the request succeeded. You can call getBody if you want to error on invalid status codes. The response has the following properties:

It also has a method getBody(encoding?) which looks like:

function getBody(encoding) {
  if (this.statusCode >= 300) {
    var err = new Error('Server responded with status code ' + this.statusCode + ':\n' + this.body.toString(encoding));
    err.statusCode = this.statusCode;
    err.headers = this.headers;
    err.body = this.body;
    throw err;
  }
  return encoding ? this.body.toString(encoding) : this.body;
}

FormData

var FormData = require('then-request').FormData;

Form data either exposes the node.js module, form-data, or the builtin browser object FormData, as appropriate.

They have broadly the same API, with the exception that form-data handles node.js streams and Buffers, while FormData handles the browser's File Objects.

License

MIT