A tiny barebones request library for browser environments. Performs only the most essential grunt work of calling XMLHttpRequest and returns a promise holding the future result. Further allows you to access the underlying XMLHttpRequest instance to perform lower level actions such as aborting the request.
Stringifies and parses JSON request payloads and responses automatically when required.
npm install micro-xhr
const xhr = require('micro-xhr');
const myRequest = xhr({
url: 'https://domain.com',
method: 'post',
headers: {
'X-My-Custom-Header': 'My custom value'
},
data: {
firstName: 'John',
lastName: 'Doe'
}
})
myRequest.then(response => {
/* Do something with response.data, response.headers or response.status */
}).catch(response => {
/* Do something with response.data, response.headers or response.status */
});
myRequest.xhr.abort(); // abort the request
Perform an HTTP(S) request to the given url, with the given method, headers and data.
- requestObject (Object)
url
(string): URL to perform the request tomethod
(string): HTTP method to use (defaults to GET)headers
(Object): Headers to use, keys are case insensitive andcontent-type
defaults toapplication/json
data
(any): Request payload to send. Automatically stringifies to JSON if thecontent-type
header containsapplication/json
.
- (Promise): Resolves when the request finalizes, except in case of a non-2XX status or on parse errors
- - resolves to (Object) -
status
(int): The received status codeheaders
(Object): Received headers, all keys are lowercasedata
(string | any): Received response body, auto-parses JSON, else returns a string
- - or rejects to (Object) -
status
(int): The received status code, 0 if request failedheaders
(Object): Received headers, all keys are lowercasedata
(string | any)?: Received response body, auto-parses JSON, else returns a stringerror
(Error)?: Returned instead ofdata
an exception occurs during parsingrawBody
(string): Unparsed response body
xhr
(XmlHttpRequest): The underlying XMLHttpRequest
- - resolves to (Object) -
The same as micro-xhr
, except that the promise still resolves on a non-2XX status. Called internally by micro-xhr