All Projects → feross → Simple Get

feross / Simple Get

Licence: mit
Simplest way to make http get requests. Supports HTTPS, redirects, gzip/deflate, streams in < 100 lines

Programming Languages

javascript
184084 projects - #8 most used programming language

Projects that are alternatives of or similar to Simple Get

Drag Drop
HTML5 drag & drop for humans
Stars: ✭ 443 (+24.09%)
Mutual labels:  browserify, browser
Yt Player
Simple, robust, blazing-fast YouTube Player API
Stars: ✭ 576 (+61.34%)
Mutual labels:  browserify, browser
Badssl.com
🔒 Memorable site for testing clients against bad SSL configs.
Stars: ✭ 2,234 (+525.77%)
Mutual labels:  https, browser
Lyo
📦 Node.js to browser - The easy way
Stars: ✭ 624 (+74.79%)
Mutual labels:  browserify, browser
Buffer
The buffer module from node.js, for the browser.
Stars: ✭ 1,178 (+229.97%)
Mutual labels:  browserify, browser
Render Media
Intelligently render media files in the browser
Stars: ✭ 181 (-49.3%)
Mutual labels:  browserify, browser
Clipboard Copy
Lightweight copy to clipboard for the web
Stars: ✭ 443 (+24.09%)
Mutual labels:  browserify, browser
Awesome Mad Science
Delightful npm packages that make you say "wow, didn't know that was possible!"
Stars: ✭ 909 (+154.62%)
Mutual labels:  browserify, browser
Connectivity
Detect if the network is up (do we have connectivity?)
Stars: ✭ 58 (-83.75%)
Mutual labels:  browserify, browser
String To Stream
Convert a string into a stream (streams2)
Stars: ✭ 75 (-78.99%)
Mutual labels:  browserify, browser
Magnet Uri
Parse a magnet URI and return an object of keys/values
Stars: ✭ 183 (-48.74%)
Mutual labels:  browserify, browser
Mochify.js
☕️ TDD with Browserify, Mocha, Headless Chrome and WebDriver
Stars: ✭ 338 (-5.32%)
Mutual labels:  browserify
Pode
Pode is a Cross-Platform PowerShell web framework for creating REST APIs, Web Sites, and TCP/SMTP servers
Stars: ✭ 329 (-7.84%)
Mutual labels:  https
Copy As Markdown
Copying Link, Image and Tab(s) as Markdown Much Easier.
Stars: ✭ 332 (-7%)
Mutual labels:  browser
Forwardproxy
Forward proxy plugin for the Caddy web server
Stars: ✭ 333 (-6.72%)
Mutual labels:  https
Extanalysis
Browser Extension Analysis Framework - Scan, Analyze Chrome, firefox and Brave extensions for vulnerabilities and intels
Stars: ✭ 351 (-1.68%)
Mutual labels:  browser
Chrome Remote Interface
Chrome Debugging Protocol interface for Node.js
Stars: ✭ 3,603 (+909.24%)
Mutual labels:  browser
Mojito
An easy-to-use Elixir HTTP client, built on the low-level Mint library.
Stars: ✭ 333 (-6.72%)
Mutual labels:  https
Espui
A simple web user interface library for ESP32 and ESP8266
Stars: ✭ 330 (-7.56%)
Mutual labels:  browser
Ffpass
Import and Export passwords for Firefox Quantum 🔑
Stars: ✭ 329 (-7.84%)
Mutual labels:  browser

simple-get travis npm downloads javascript style guide

Simplest way to make http get requests

features

This module is the lightest possible wrapper on top of node.js http, but supporting these essential features:

  • follows redirects
  • automatically handles gzip/deflate responses
  • supports HTTPS
  • supports specifying a timeout
  • supports convenience url key so there's no need to use url.parse on the url when specifying options
  • composes well with npm packages for features like cookies, proxies, form data, & OAuth

All this in < 100 lines of code.

install

npm install simple-get

usage

Note, all these examples also work in the browser with browserify.

simple GET request

Doesn't get easier than this:

const get = require('simple-get')

get('http://example.com', function (err, res) {
  if (err) throw err
  console.log(res.statusCode) // 200
  res.pipe(process.stdout) // `res` is a stream
})

even simpler GET request

If you just want the data, and don't want to deal with streams:

const get = require('simple-get')

get.concat('http://example.com', function (err, res, data) {
  if (err) throw err
  console.log(res.statusCode) // 200
  console.log(data) // Buffer('this is the server response')
})

POST, PUT, PATCH, HEAD, DELETE support

For POST, call get.post or use option { method: 'POST' }.

const get = require('simple-get')

const opts = {
  url: 'http://example.com',
  body: 'this is the POST body'
}
get.post(opts, function (err, res) {
  if (err) throw err
  res.pipe(process.stdout) // `res` is a stream
})

A more complex example:

const get = require('simple-get')

get({
  url: 'http://example.com',
  method: 'POST',
  body: 'this is the POST body',

  // simple-get accepts all options that node.js `http` accepts
  // See: http://nodejs.org/api/http.html#http_http_request_options_callback
  headers: {
    'user-agent': 'my cool app'
  }
}, function (err, res) {
  if (err) throw err

  // All properties/methods from http.IncomingResponse are available,
  // even if a gunzip/inflate transform stream was returned.
  // See: http://nodejs.org/api/http.html#http_http_incomingmessage
  res.setTimeout(10000)
  console.log(res.headers)

  res.on('data', function (chunk) {
    // `chunk` is the decoded response, after it's been gunzipped or inflated
    // (if applicable)
    console.log('got a chunk of the response: ' + chunk)
  }))

})

JSON

You can serialize/deserialize request and response with JSON:

const get = require('simple-get')

const opts = {
  method: 'POST',
  url: 'http://example.com',
  body: {
    key: 'value'
  },
  json: true
}
get.concat(opts, function (err, res, data) {
  if (err) throw err
  console.log(data.key) // `data` is an object
})

Timeout

You can set a timeout (in milliseconds) on the request with the timeout option. If the request takes longer than timeout to complete, then the entire request will fail with an Error.

const get = require('simple-get')

const opts = {
  url: 'http://example.com',
  timeout: 2000 // 2 second timeout
}

get(opts, function (err, res) {})

One Quick Tip

It's a good idea to set the 'user-agent' header so the provider can more easily see how their resource is used.

const get = require('simple-get')
const pkg = require('./package.json')

get('http://example.com', {
  headers: {
    'user-agent': `my-module/${pkg.version} (https://github.com/username/my-module)`
  }
})

Proxies

You can use the tunnel module with the agent option to work with proxies:

const get = require('simple-get')
const tunnel = require('tunnel')

const opts = {
  url: 'http://example.com',
  agent: tunnel.httpOverHttp({
    proxy: {
      host: 'localhost'
    }
  })
}

get(opts, function (err, res) {})

Cookies

You can use the cookie module to include cookies in a request:

const get = require('simple-get')
const cookie = require('cookie')

const opts = {
  url: 'http://example.com',
  headers: {
    cookie: cookie.serialize('foo', 'bar')
  }
}

get(opts, function (err, res) {})

Form data

You can use the form-data module to create POST request with form data:

const fs = require('fs')
const get = require('simple-get')
const FormData = require('form-data')
const form = new FormData()

form.append('my_file', fs.createReadStream('/foo/bar.jpg'))

const opts = {
  url: 'http://example.com',
  body: form
}

get.post(opts, function (err, res) {})

Or, include application/x-www-form-urlencoded form data manually:

const get = require('simple-get')

const opts = {
  url: 'http://example.com',
  form: {
    key: 'value'
  }
}
get.post(opts, function (err, res) {})

Specifically disallowing redirects

const get = require('simple-get')

const opts = {
  url: 'http://example.com/will-redirect-elsewhere',
  followRedirects: false
}
// res.statusCode will be 301, no error thrown
get(opts, function (err, res) {})

Basic Auth

const user = 'someuser'
const pass = 'pa$$word'
const encodedAuth = Buffer.from(`${user}:${pass}`).toString('base64')

get('http://example.com', {
  headers: {
    authorization: `Basic ${encodedAuth}`
  }
})

OAuth

You can use the oauth-1.0a module to create a signed OAuth request:

const get = require('simple-get')
const crypto  = require('crypto')
const OAuth = require('oauth-1.0a')

const oauth = OAuth({
  consumer: {
    key: process.env.CONSUMER_KEY,
    secret: process.env.CONSUMER_SECRET
  },
  signature_method: 'HMAC-SHA1',
  hash_function: (baseString, key) => crypto.createHmac('sha1', key).update(baseString).digest('base64')
})

const token = {
  key: process.env.ACCESS_TOKEN,
  secret: process.env.ACCESS_TOKEN_SECRET
}

const url = 'https://api.twitter.com/1.1/statuses/home_timeline.json'

const opts = {
  url: url,
  headers: oauth.toHeader(oauth.authorize({url, method: 'GET'}, token)),
  json: true
}

get(opts, function (err, res) {})

Throttle requests

You can use limiter to throttle requests. This is useful when calling an API that is rate limited.

const simpleGet = require('simple-get')
const RateLimiter = require('limiter').RateLimiter
const limiter = new RateLimiter(1, 'second')

const get = (opts, cb) => limiter.removeTokens(1, () => simpleGet(opts, cb))
get.concat = (opts, cb) => limiter.removeTokens(1, () => simpleGet.concat(opts, cb))

var opts = {
  url: 'http://example.com'
}

get.concat(opts, processResult)
get.concat(opts, processResult)

function processResult (err, res, data) {
  if (err) throw err
  console.log(data.toString())
}

license

MIT. Copyright (c) Feross Aboukhadijeh.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].