npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

q-xhr

v1.1.0

Published

XMLHttpRequest (ajax) using powerful Q promises

Downloads

1,910

Readme

q-xhr: Do ajax with powerful Q promises

Deprecation Notice

In 2014, Q was an amazing library pushing promises and helping us all do asyncronous programming better. Now however that Promise is part of ES6, and widely available natively in modern browsers and Node.js, and that Q has a vastly different API, we should just use the standard Promise library. Axios does that using the same API inspired from Angular's $http, so I encorage you to migrate to that library. It's great.

Build Status

SauceLabs Test Status

Why q-xhr and not $.ajax?

jQuery promises have flaws that make them Promises/A+ compliant and they are not going to be fixed. Q also has a lot more functions for promise manipluation and management.

Once you have a good MVC framework, taking a dependency on a 94kb minified (1.11) library just for $.ajax is alot, expecially when Q is 19k minified (probably half if you remove the node.js specifics). For example, Knockout 3.0 is 45k minified, and includes support all the way back to IE6 - and you can structure your code properly with it instead of creating spaghetti code coupled to the DOM.

Examples

Get some JSON:

  Q.xhr.get('/status').done(function(resp) {
    console.log('status is ' + resp.data)
  })

Post some JSON:

  Q.xhr.post('/greet', {
    say: 'hello'
  }).then(function(resp) {
    console.log('success!')
  }, function(resp) {
    console.log('request failed with status' + resp.status)
  })

Listen to progress:


  var someLargeData = getSomeLargeData();

  Q.xhr.post('/processLargeData', someLargeData).progress(function(progress) {
    if (progress.upload) {
      console.log('Uploaded: '+progress.loaded+' bytes')
    } else {
      console.log('Downloaded: '+progress.loaded+' bytes')
    }
  }).then(function(resp) {
    console.log('success!')
  })

With modern web applications in mind, application/json is the default mime type.

Differences from Angular's $http

On the topic of MVC frameworks not needing jQuery, The Angular devs have adopted Q throught, and their http service uses Q. q-xhr is a fork of that, with the following differences:

  • No built-in caching. Caching is a separate responsibility outside of doing ajax calls. Hooks are provided to bring your own caching library or mechanism - see below.
  • No JSONP. JSONP has all sorts of security flaws and limitations and causes lots of burden on both client side and server side code. Given that XDomainRequest is available for IE8 and 9, and IE6 and 7 are dead, it should be avoided IMO. If you want XDomainRequest support (which jQuery never did), let me know or submit a pull request!
  • Interceptors are applied in order. I guess angular had some backward compatibility they were tied to do so something funky by applying request handlers in reverse but response handlers in order, but I don't have backward compatibility issues so it works like you'd expect.
  • The default JSON transform is only applied if the response content is application/json. Angular was doing something odd by sniffing all content via regex matching and then converting it to JSON if it matched. Why? Geez people set your Content-Type correctly already. Not to mention content sniffing leads to security issues.
  • Progress support. Supply a progress listener function to recieve ProgressEvents. q-xhr listens to both upload and download progress. To help you detect the type of progress, q-xhr adds the boolean property upload to the ProgressEvent object.

Installation

Bower

bower install q-xhr

npm

npm install q-xhr

Usage

browserify

var Q = require('q-xhr')(window.XMLHttpRequest, require('q'))
Q.xhr.get('https://api.github.com/users/nathanboktae/events').then(.....)

AMD

Assuming that q-xhr.js and q.js are in your baseUrl

require(['q-xhr'], function(Q) {
  Q.xhr.get('https://api.github.com/users/nathanboktae/events').then(.....)
})

Plain old scripts

<script src="q.js"></script>
<script src="q-xhr.js"></script>
<script>
  Q.xhr.get('https://api.github.com/users/nathanboktae/events').then(.....)
</script>

Cache Hooks

A cache object can be provided either as defaults on Q.xhr.defaults or per-request (with the per-request object preferred). The object must have a get function that returns the response object for a url, and a put function given the url and response object to save it. The most trival implementation would be this:

var cache = {}
Q.xhr.defaults.cache = {
  get: function(url) {
    return cache[url]
  },
  put: function(url, response) {
    cache[url] = response
  }
}

Unlike $http, q-xhr will not put pending requests in the cache - only successful responses, and before transforms are applied (they will be re-applied each retrieval).

Upload Progress

Assigning a handler to xhr.upload.onprogress in Chrome causes it to issue a preflight request which requires additional handling on the part of the server. If you don't track upload progress and want to avoid this incompatibility, add option disableUploadProgress: true to your q-xhr options.