axios / axios Goto Github PK
View Code? Open in Web Editor NEWPromise based HTTP client for the browser and node.js
Home Page: https://axios-http.com
License: MIT License
Promise based HTTP client for the browser and node.js
Home Page: https://axios-http.com
License: MIT License
Getting this error in node after updating.
Seems to be loading xhr and barfing on this:
var msie = /(msie|trident)/i.test(navigator.userAgent);
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.
Cannot pass response, status, headers, and config to resolve
/reject
as a result. See #6
in https://github.com/mzabriskie/axios/blob/master/lib/utils.js#L148
// Check if obj is array-like
var isArray = obj.constructor === Array || typeof obj.callee === "function";
when using webpack bundle in strict mode that contains axios.standalone.js (i use bluebird Promise)
It would be nice to see support for deflating/gunzipping requests. Have you thought about this?
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.
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.
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
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?
I would like to intercept a request and then pre-emptively resolve with a response (compare https://github.com/trek/pretender). Is there an example of this being done elsewhere?
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!
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.
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?
So this can rock both frontend and backend ๐
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?
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>`
When using PATCH
, POST
, or PUT
if the content isn't JSON the Content-Type
header is still sent as application/json;charset=utf-8
.
It looks like I'm having the same issues as here:
deployd/deployd#126
I can't do a cross origin XHR because the X-Requested-With header is set. But I can't disable it.
Bundling for browsers includes http
from node resulting in massive file size.
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
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;
});
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.
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.
As suggested by @geddski. See docs for superaget's api here
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();
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?
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?
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?
If I am building with Babel, will the polyfill still get included?
Perf isn't that much better using RegExp before hand to determine if String is JSON. This also causes problems b/c YAML can look like JSON in some cases, but throws an Exception when attempting to parse. If using try/catch is needed for the second case anyway, just abandon the RegExp all together.
Benchmarks: https://gist.github.com/mzabriskie/fe85e6ea69b5049d17dd
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.
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).
What do you think about returning promises from transforms? I have a case where I need to perform some async operation in a transform.
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.
Will implement using https://github.com/mzabriskie/felix
axios.all(axios.get(...), axios.get(...))
.then(function (results) {
// This never gets called
});
See Angular's spec for reference https://docs.angularjs.org/api/ng/service/$http#interceptors
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.
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
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
hi,
I was wondering if there is a way to configure the default timeout for axios requests?
thanks,
chris
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.
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
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.
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?
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.
Multibyte characters on chunk boundaries get corrupted.
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);
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.