Coder Social home page Coder Social logo

axios / axios Goto Github PK

View Code? Open in Web Editor NEW
104.0K 104.0K 10.7K 14.88 MB

Promise based HTTP client for the browser and node.js

Home Page: https://axios-http.com

License: MIT License

JavaScript 87.05% HTML 1.69% TypeScript 11.04% Handlebars 0.22%
hacktoberfest http-client javascript nodejs promise

axios's Issues

axios.all doesn't work

axios.all(axios.get(...), axios.get(...))
  .then(function (results) {
    // This never gets called
  });

route-specific interceptors

Perhaps there is already a way to do this. It would be nice to be able to do route-specific interceptors in a express-familiar style, such as:

var axios = require('axios')
axios.interceptors.request.use('/foo', function(config) {
  // ...
})

This is relevant to me lately since I want to put a client-only caching layer in front of my isomorphic controllers in a React app.

unhandled 'error' event in node

When making a request to a url that doesn't exist, axios crashes the server on an unhandled 'error' event.

var axios = require('axios');

axios.post('http://google.com').then(function(response) {
    console.log('woo a response', response);
  })
  .catch(function(response) {
    console.log('hrrm, an error', repsonse);
  });

// needed to prevent node from immediately exiting without actually making the request
setTimeout(function() {
  console.log('what in the world, why isn\'t this waiting to exit')
}, 5000);

It looks like the problem is no req.on('error') handler on https://github.com/mzabriskie/axios/blob/1d6430f667486ca9de390ccec242114b36c41377/lib/adapters/http.js#L80.

I'm not sure the best way to handle an error here though, since it doesn't fit the expected {data, status, headers, config} type of message the reject handler expects.

Deflate/gunzip

It would be nice to see support for deflating/gunzipping requests. Have you thought about this?

posting with formdata not working

tried doing something like

var fileData = new FormData();
      fileData.append("File1", file);

return axios({
                    method: 'post',
                    url: response.data.ChunkUri,
                    data: fileData,

                });

this returned an error from the server saying that there was no file sent. But...

vs jquery which worked and the file uploaded successfully.


                var options = {
                    type: "POST",
                    url: response.data.ChunkUri,
                    data: fileData,
                    cache: false,
                    contentType: false,
                    processData: false,
                    success: function(e){
                            console.log("YAY:: " + e);
                    },
                    error: function(a){
                        console.log("failed:: ");
                    }

                };
                return $.ajax(options);

How to handle error from JSON.parse

The transformRequest method attempts to parse JSON, but swallows any error in an empty catch statement. This results in the stringified form of the response body to be returned should the JSON be malformed, and supplied to the response object that is used to resolve the Promise.

Without the try/catch a global error would occur. With the try/catch the code handling the response will error, but in an unpredictable way. Consider:

// Assume a malformed response from the server for the request.
// Missing quotes around property names:
//   {firstName: "Jimmy", lastName: "Page", isBlocked: true}
axios.get('/user/12345').then((res) => {
  var user = res.data;
  if (!user.isBlocked) {
    // Do something potentially dangerous that only an unblocked user should be allowed to do
  }
});

In this case user is a String not an Object as expected. Calling 'some string'.isBlocked will return undefined, which evaluates as falsey. This will cause the if condition to erroneously be entered.

A potential solution would be to reject the Promise if JSON.parse throws an Error. This isn't a straight forward fix though as it would break #55 again.

SSL Support in Node

Hi,

Awesome job on axios. One question I have is, is https compatibility in Node something that you would consider for this package? Currently, it looks like there is just an http adapter. Would you consider https and if so, would you consider a flag to ignore self signed ssl certs?

Thanks much!

Provide .done() or other method to throw Exception out of chain

Consider this code:

// fragment of react-based app

Axios.get('/api/robots/')
  .then((res) => { // could be .done() if... see below
    let self = this;
    //setTimeout(function() { // -- this is ugly disabled workaround --
      self.setState(res.data); // if error happen here
    //}, 1);
    console.log(">>> RobotStore.state:", this.state);
  })
  .catch((res) => {
    if (res instanceof Error) { // it is catched here
      // unpredictable error, release 
      throw Error("test"); // this DOES NOT work, error is swallowed (reject promise which is never used)
    } else {
      // HTTP error, handle
      this.setState(this.getInitialState());
    }
  }); 

So axios (actually ES6 Promise engine) swallows app errors (which I want to bubble up and crash everything, as it's not runtime error).

http://bahmutov.calepin.co/why-promises-need-to-be-done.html

But looks like done still is not a part of spec and "ugly workaround" is required. Some authors insist on deprecating done at all.

http://stackoverflow.com/questions/26667598/will-javascript-es6-promise-support-done-api

I'ml aware of all aspects of this subject. What can you propose to solve this issue?
Monkeypatch .done? Leave setTimeout "trick" as it is? Or there are other ways?

Set response encoding

I wanted to get a buffer out of some binary data from a GET request but I couldn't get it to work unless I put res.setEncoding('binary') inside http.js
Any suggestions?

No Clear way to abort XmlHttpRequest

Is there a simple way to expose the XHR object so that it can be aborted, or is this better off being handled somehow in a response interceptor?

Provide access to the response's statusText

As far I can see it is currently only possible to access the status code.
It would be great if it would be possible to also access the statusText especially when the request fails.

NodeJS - Cookie Jar Support

axios running on NodeJS does not provide Cookie jar support natively. Ideally the library would either provide built in cookie jar functionality or easily accommodate existing cookie jar libraries.

The Request API could be modified to support the following options:

{
...
  // `jar` is a boolean that controls cookie jar support for the request
  jar: true, // default
...
}

or

{
...
  // `jar` is a cookie jar that will be used for the request
  jar: cookieJar, // default
...
}

where

var tough = require('tough-cookie');
var cookiejar = new tough.CookieJar();

Note:
Trivial cookie support using tough-cookie can be added by leveraging interceptors:

var tough = require('tough-cookie');
var Cookie = tough.Cookie;
var cookiejar = new tough.CookieJar();

axios.interceptors.request.use(function (config) {
  cookiejar.getCookies(config.url, function(err, cookies) {
    config.headers.cookie = cookies.join('; ');
  });
  return config;
});

axios.interceptors.response.use(function (response) {
  if (response.headers['set-cookie'] instanceof Array) {
    cookies = response.headers['set-cookie'].forEach(function (c) {
      cookiejar.setCookie(Cookie.parse(c), response.config.url, function(err, cookie){});
    });
  }
  return response;
});

Support "foo" as valid json

As for
var JSON_START = /^\s*([|{[^{])/;
in defaults.js

I think "foo" is also a valid json, so I think you should include " in your JSON_START and JSON_STOP

Lowercase PATCH verb sent in CORS preflight request result in a rejected method when the server responds with an uppercase PATCH allow-methods

For cross-origin requests the browser usually sends a preflight OPTIONS request. This request usually asks "Can I use method POST for this resource?" among other questions, by specifying a Access-Control-Request-Headers: POST.

The server will then respond with Access-Control-Allow-Methods: GET, POST allowing the method.

With axios, sending a patch request creates a Access-Control-Request-Headers: patch request, and if the server responds with Access-Control-Allow-Methods: PATCH, the created XmlHttpRequest does not send an uppercase PATCH verb, but sends a lowercase one, and the browser decides to disallow the request.

This occurs only with PATCH. The reason for this is unclear, but on Chrome 39 on Firefox 33 it seems that all verbs are auto-corrected to uppercase with the exception of PATCH.

Why is this an issue? Because according to the spec, HTTP verbs are case-sensitive, and should be uppercase by default.

http://www.ietf.org/rfc/rfc2616.txt

The Method token indicates the method to be performed on the resource identified by the Request-URI. The method is case-sensitive.
[list of HTTP methods, GET, POST ...]

Thus, the culprit is in fact both in axios and browsers: because browsers tend to uppercase the preflight verbs (but patch seems to be omitted, I have not tested other verbs), and axios sends a lowercase method parameter here.

I think the simplest fix would just be to set the line to method: method.toUpperCase(). This fixed it for me.

Cannot run specs: ReferenceError: Can't find variable: getJasmineRequireObj

Finally got time to work on #21

but I'm unable to run specs. I get following error on the current master (7efc095):

epeli@axiostrusty ~/axios
(master|!โšก)$ npm test

> [email protected] test /home/epeli/axios
> grunt test

Running "webpack:global" (webpack) task
Version: webpack 1.5.3      
    Asset   Size  Chunks             Chunk Names
 axios.js  56527       0  [emitted]  main
axios.map  67647       0  [emitted]  main

Running "nodeunit:all" (nodeunit) task
Testing http.js..OK
Testing buildUrl.js.......OK
Testing defaults.js....OK
Testing parseHeaders.js.OK
Testing spread.js.OK
Testing transformData.js..OK
Testing forEach.js....OK
Testing isX.js......OK
Testing merge.js..OK
Testing trim.js..OK
>> 46 assertions passed (94ms)

Running "karma:single" (karma) task
INFO [karma]: Karma v0.12.31 server started at http://localhost:9876/
INFO [launcher]: Starting browser PhantomJS
INFO [PhantomJS 1.9.8 (Linux)]: Connected on socket b6e-nUZdVz5M2DH6pJbA with id 65106151
PhantomJS 1.9.8 (Linux) ERROR
  ReferenceError: Can't find variable: getJasmineRequireObj
  at /home/epeli/axios/node_modules/karma-jasmine-ajax/node_modules/jasmine-ajax/lib/mock-ajax.js:33


Warning: Task "karma:single" failed. Use --force to continue.

Aborted due to warnings.
npm ERR! Test failed.  See above for more details.
npm ERR! not ok code 0
epeli@axiostrusty ~/axios
(master|!โšก)$ 

I'm on 64bit Ubuntu Trusty. Any ideas what I'm missing?

Support named results in .all

Like async's parallel. So it could go from this:

axios.all([getUserAccount(), getUserPermissions()])
    .then(axios.spread(function (acct, perms) {
        // Both requests are now complete
    }));

to this:

axios.all({ acct: getUserAccount(), perms: getUserPermissions()})
    .then(function (results) {
        // Both requests are now complete
        var acct = results.acct;
        var perms = results.perms;
    });

This makes adding new requests to all simpler because you don't have to keep track of the order of items. This is how I normally do stuff when I use async. Just thought I'd suggest it.

Babel with Axios

Hi, I'm using Webpack to build our scripts. We are also using Babel's polyfill (browser polyfill). While building the scripts in Ubuntu Server 14.04, I encounter this:

Cannot resolve module `vertx` in <path/to/es6-promise/dist>`

Timeout configuration?

hi,
I was wondering if there is a way to configure the default timeout for axios requests?

thanks,
chris

Allow build without es6 promise polyfill

Great stuff! This seem to be the only lib I found that actually use native es6 promise with proper responseType for xhr2.

One suggestion: we actually manage polyfills separately, would be great to have a build without polyfill bundled to save some bytes.

Async transforms

What do you think about returning promises from transforms? I have a case where I need to perform some async operation in a transform.

question: having problem posting object

i have (coffeescript) code like this running in a browser:

    axios.post @props.url, {foo: 'bar'}
    .then (res) =>
      dbg 'handle-comment-submit: res=%o', res
      @setState data: res.data
    .catch (err) ->
      console.error 'handle-comment-submit: err=%o', err

and server side code like this running in a gulp task:

gulp.task 'server', ->
  gulp.src buildApp
  .pipe plug.webserver(
    livereload: false
    directoryListing: false
    open: true
    middleware: [
      bodyParser.urlencoded extended: false

      (req, res, next) ->
        dbg 'middleware: url=%s, method=%s', req.url, req.method
        if (req.url == '/comments.json') and (req.method == 'POST')
          fileName = "#{buildApp}/comments.json"
          fs.readFile fileName, (err, data) ->
            if err
              console.log 'read-file: err=%o', err
            comments = JSON.parse data
            dbg 'middleware: comments=%o, body=%o', comments, req.body # <--------
            comments.push req.body
            fs.writeFile fileName, JSON.stringify(comments, null, 4), (err) ->
              if err
                console.log 'write-file: err=%o', err
              res.setHeader 'Content-Type', 'application/json'
              res.setHeader 'Cache-Control', 'no-cache'
              res.end JSON.stringify(comments)
        else
          next()
    ]

the log message with the <------- shows that body is empty like {}

but when using the following jquery code in the browser, the body is as expected:

$.ajax
      url: @props.url
      dataType: 'json'
      type: 'POST'
      data: comment
      success: (data) =>
        dbg 'handle-comment-submit: data=%o', data
        @setState data: data
      error: (xhr, status, err) =>
        console.error @props.url, status, err.toString()

i'm sure i'm being a dunce, but any guidance as to what i might do to get the desired effect with axios?

regards,
tony

node.js exits before request finishes

I found this trying to reproduce a separate issue. It could also be because I'm doing something dumb.

var axios = require('axios');
axios.get('/durp').then(function(res) { console.log('response is', res);}).catch(function(res) { console.log('err response is', res);});

If you run this in node v0.10.25 and axios v0.4.0, node will just exit immediately before calling either callback.

Getting the XHR instance

Hmm, I'm currently implementing a progress bar with xhr.upload. I just checked the docs, but I couldn't squeeze out any info at all. Is the instance exposed with the latest versions?

Use it with almond

Hi,

I would like to be able to do a require('axios') with almond. The file is correctly found but the result of the require is always undefined (even with axios.amd or axios.standalone). Do you have any insights on this?

Nice lib by the way!

Thanks

Robin

Support finally?

Would it be feasible to support finally? Ie.

axios.get(...).then(...).catch(...).finally(...);

It would get triggered in both then/catch cases and seems to be common in Promise implementations (handy for cleanup).

Question: Getting the headers for tests

I feel like this is out of topic, though. Anyway --

I'm implementing JWT with Axios, and would like to send the Authorization Header through the interceptor. Question, how do I test with Sinon that I am able to send the said header? Which do I spy? Thanks.

Edit: I just checked the API, and the headers doesn't seem to be covered in the interceptors. In the Interceptors example, is config equal to the whole request API or just the config in it?

Don't throw an error on bad status code

I saw issue #24 and promptly agreed, opening PR #32. However, after some more playing around with this lib, I realized that throwing an error on a non 200 status code doesn't make much sense to me. Shouldn't that validation be done on the consumer-side? I started using axios for tests and realized that it screws with those that need to verify some sort of validation (i.e. tests that expect non-200 error codes).

Considering how easy it is to layer functionality with promises, this really seems like something a consumer of axios should explicitly decide

Configure the promise implementation

I wish to provide my own Promise implementation (core-js), so I do not want browserify do bundle the es6-promise module. Is there a simple way to configure axios not to require this module?

// Polyfill ES6 Promise if needed
require('es6-promise').polyfill();

ES6-Promise

If I am building with Babel, will the polyfill still get included?

FormData() with 'Content-Type': 'multipart/form-data'?

Trying to send an image across the network. Can't figure out what isn't working.
Headers:

{ 'Content-Type': 'multipart/form-data' }

Content is a FormData Blob object:

https://developer.mozilla.org/en-US/docs/Web/Guide/Using_FormData_Objects

using the request API with

{url: '...', method: 'put', data: blob, headers: {}}

Data seems to get swallowed up and not sent by axios. Body reported by chrome as {}.

This was working with the 'rest' package before I switched over.

Any idea what might be going wrong?

http not posting data in node

axios({ 
  url: 'http://requestb.in/ubgv1aub',
  data: { test: true }
})

successfully posts but the request body is empty. Probably missing some headers, but setting Content-Type and Content-Length manually cause axios to hang for some reason.

Standalone build possibly broken

Hello there,

I'm trying to use axios.standalone.js in Chrome 39 (which has built-in Promise) and have been getting the following error:

Uncaught TypeError: Cannot read property 'Promise' of undefined

Which traces back to https://github.com/mzabriskie/axios/blob/master/dist/axios.standalone.js#L54, as follows:

    /* WEBPACK VAR INJECTION */(function(process) {var Promise = __webpack_require__(2).Promise;

However, __webpack_require__(2) is undefined, as https://github.com/mzabriskie/axios/blob/master/dist/axios.standalone.js#L161 suggests,

/***/ function(module, exports, __webpack_require__) {

    module.exports = undefined;

/***/ },

Can this possibly be a bug?

Regards,

xkxx

Reject with error

It is good practice to reject promises with an error object because they have stack traces.

When rejecting because of a bad status code, I suggest rejecting with an error object, e.g. BadStatusCodeError. You could then attach the response object to the error object so it can be accessed in a rejection handler.

Catching errors from other things

The .catch from one ajax call is catching errors completely unrelated. One time I had required a file that did not exist, and it was being caught inside a module that I was making an ajax request in using axios. Promises seem to be messed up.

Don't throw error / catch on 400-level responses

Instead, limit the error/catch to 500-level errors. 400-level responses can be completely valid, expected, desired, etc.

I have been following this pattern with my bunyan logging -- logging 400-level responses as warnings, and 500-level responses as errors. The idea is that a successful npm test (which may expect 400-level responses) should show zero logging errors.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.