Axios js

Axios js DEFAULT

npm

npm versionCDNJSBuild statusGitpod Ready-to-Codecode coverageinstall sizenpm downloadsgitter chatcode helpers

Promise based HTTP client for the browser and node.js

New axios docs website: click here

Table of Contents

Features

  • Make XMLHttpRequests from the browser
  • Make http requests from node.js
  • Supports the Promise API
  • Intercept request and response
  • Transform request and response data
  • Cancel requests
  • Automatic transforms for JSON data
  • Client side support for protecting against XSRF

Browser Support

Browser Matrix

Installing

Using npm:

Using bower:

Using yarn:

Using jsDelivr CDN:

<scriptsrc="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>

Using unpkg CDN:

<scriptsrc="https://unpkg.com/axios/dist/axios.min.js"></script>

Example

note: CommonJS usage

In order to gain the TypeScript typings (for intellisense / autocomplete) while using CommonJS imports with use the following approach:

constaxios=require('axios').default;// axios.<method> will now provide autocomplete and parameter typings

Performing a request

constaxios=require('axios');// Make a request for a user with a given IDaxios.get('/user?ID=12345').then(function(response){// handle successconsole.log(response);}).catch(function(error){// handle errorconsole.log(error);}).then(function(){// always executed});// Optionally the request above could also be done asaxios.get('/user',{params: {ID: 12345}}).then(function(response){console.log(response);}).catch(function(error){console.log(error);}).then(function(){// always executed});// Want to use async/await? Add the `async` keyword to your outer function/method.asyncfunctiongetUser(){try{constresponse=awaitaxios.get('/user?ID=12345');console.log(response);}catch(error){console.error(error);}}

NOTE: is part of ECMAScript 2017 and is not supported in Internet Explorer and older browsers, so use with caution.

Performing a request

axios.post('/user',{firstName: 'Fred',lastName: 'Flintstone'}).then(function(response){console.log(response);}).catch(function(error){console.log(error);});

Performing multiple concurrent requests

functiongetUserAccount(){returnaxios.get('/user/12345');}functiongetUserPermissions(){returnaxios.get('/user/12345/permissions');}Promise.all([getUserAccount(),getUserPermissions()]).then(function(results){constacct=results[0];constperm=results[1];});

axios API

Requests can be made by passing the relevant config to .

axios(config)
// Send a POST requestaxios({method: 'post',url: '/user/12345',data: {firstName: 'Fred',lastName: 'Flintstone'}});
// GET request for remote image in node.jsaxios({method: 'get',url: 'http://bit.ly/2mTM3nY',responseType: 'stream'}).then(function(response){response.data.pipe(fs.createWriteStream('ada_lovelace.jpg'))});
axios(url[, config])
// Send a GET request (default method)axios('/user/12345');

Request method aliases

For convenience aliases have been provided for all supported request methods.

axios.request(config)
axios.get(url[, config])
axios.delete(url[, config])
axios.head(url[, config])
axios.options(url[, config])
axios.post(url[, data[, config]])
axios.put(url[, data[, config]])
axios.patch(url[, data[, config]])
NOTE

When using the alias methods , , and properties don't need to be specified in config.

Concurrency (Deprecated)

Please use to replace the below functions.

Helper functions for dealing with concurrent requests.

axios.all(iterable) axios.spread(callback)

Creating an instance

You can create a new instance of axios with a custom config.

axios.create([config])
constinstance=axios.create({baseURL: 'https://some-domain.com/api/',timeout: 1000,headers: {'X-Custom-Header': 'foobar'}});

Instance methods

The available instance methods are listed below. The specified config will be merged with the instance config.

axios#request(config)
axios#get(url[, config])
axios#delete(url[, config])
axios#head(url[, config])
axios#options(url[, config])
axios#post(url[, data[, config]])
axios#put(url[, data[, config]])
axios#patch(url[, data[, config]])
axios#getUri([config])

Request Config

These are the available config options for making requests. Only the is required. Requests will default to if is not specified.

{// `url` is the server URL that will be used for the requesturl: '/user',// `method` is the request method to be used when making the requestmethod: 'get',// default// `baseURL` will be prepended to `url` unless `url` is absolute.// It can be convenient to set `baseURL` for an instance of axios to pass relative URLs// to methods of that instance.baseURL: 'https://some-domain.com/api/',// `transformRequest` allows changes to the request data before it is sent to the server// This is only applicable for request methods 'PUT', 'POST', 'PATCH' and 'DELETE'// The last function in the array must return a string or an instance of Buffer, ArrayBuffer,// FormData or Stream// You may modify the headers object.transformRequest: [function(data,headers){// Do whatever you want to transform the datareturndata;}],// `transformResponse` allows changes to the response data to be made before// it is passed to then/catchtransformResponse: [function(data){// Do whatever you want to transform the datareturndata;}],// `headers` are custom headers to be sentheaders: {'X-Requested-With': 'XMLHttpRequest'},// `params` are the URL parameters to be sent with the request// Must be a plain object or a URLSearchParams objectparams: {ID: 12345},// `paramsSerializer` is an optional function in charge of serializing `params`// (e.g. https://www.npmjs.com/package/qs, http://api.jquery.com/jquery.param/)paramsSerializer: function(params){returnQs.stringify(params,{arrayFormat: 'brackets'})},// `data` is the data to be sent as the request body// Only applicable for request methods 'PUT', 'POST', 'DELETE , and 'PATCH'// When no `transformRequest` is set, must be of one of the following types:// - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams// - Browser only: FormData, File, Blob// - Node only: Stream, Bufferdata: {firstName: 'Fred'},// syntax alternative to send data into the body// method post// only the value is sent, not the keydata: 'Country=Brasil&City=Belo Horizonte',// `timeout` specifies the number of milliseconds before the request times out.// If the request takes longer than `timeout`, the request will be aborted.timeout: 1000,// default is `0` (no timeout)// `withCredentials` indicates whether or not cross-site Access-Control requests// should be made using credentialswithCredentials: false,// default// `adapter` allows custom handling of requests which makes testing easier.// Return a promise and supply a valid response (see lib/adapters/README.md).adapter: function(config){/* ... */},// `auth` indicates that HTTP Basic auth should be used, and supplies credentials.// This will set an `Authorization` header, overwriting any existing// `Authorization` custom headers you have set using `headers`.// Please note that only HTTP Basic auth is configurable through this parameter.// For Bearer tokens and such, use `Authorization` custom headers instead.auth: {username: 'janedoe',password: 's00pers3cret'},// `responseType` indicates the type of data that the server will respond with// options are: 'arraybuffer', 'document', 'json', 'text', 'stream'// browser only: 'blob'responseType: 'json',// default// `responseEncoding` indicates encoding to use for decoding responses (Node.js only)// Note: Ignored for `responseType` of 'stream' or client-side requestsresponseEncoding: 'utf8',// default// `xsrfCookieName` is the name of the cookie to use as a value for xsrf tokenxsrfCookieName: 'XSRF-TOKEN',// default// `xsrfHeaderName` is the name of the http header that carries the xsrf token valuexsrfHeaderName: 'X-XSRF-TOKEN',// default// `onUploadProgress` allows handling of progress events for uploads// browser onlyonUploadProgress: function(progressEvent){// Do whatever you want with the native progress event},// `onDownloadProgress` allows handling of progress events for downloads// browser onlyonDownloadProgress: function(progressEvent){// Do whatever you want with the native progress event},// `maxContentLength` defines the max size of the http response content in bytes allowed in node.jsmaxContentLength: 2000,// `maxBodyLength` (Node only option) defines the max size of the http request content in bytes allowedmaxBodyLength: 2000,// `validateStatus` defines whether to resolve or reject the promise for a given// HTTP response status code. If `validateStatus` returns `true` (or is set to `null`// or `undefined`), the promise will be resolved; otherwise, the promise will be// rejected.validateStatus: function(status){returnstatus>=200&&status<300;// default},// `maxRedirects` defines the maximum number of redirects to follow in node.js.// If set to 0, no redirects will be followed.maxRedirects: 5,// default// `socketPath` defines a UNIX Socket to be used in node.js.// e.g. '/var/run/docker.sock' to send requests to the docker daemon.// Only either `socketPath` or `proxy` can be specified.// If both are specified, `socketPath` is used.socketPath: null,// default// `httpAgent` and `httpsAgent` define a custom agent to be used when performing http// and https requests, respectively, in node.js. This allows options to be added like// `keepAlive` that are not enabled by default.httpAgent: newhttp.Agent({keepAlive: true}),httpsAgent: newhttps.Agent({keepAlive: true}),// `proxy` defines the hostname, port, and protocol of the proxy server.// You can also define your proxy using the conventional `http_proxy` and// `https_proxy` environment variables. If you are using environment variables// for your proxy configuration, you can also define a `no_proxy` environment// variable as a comma-separated list of domains that should not be proxied.// Use `false` to disable proxies, ignoring environment variables.// `auth` indicates that HTTP Basic auth should be used to connect to the proxy, and// supplies credentials.// This will set an `Proxy-Authorization` header, overwriting any existing// `Proxy-Authorization` custom headers you have set using `headers`.// If the proxy server uses HTTPS, then you must set the protocol to `https`. proxy: {protocol: 'https',host: '127.0.0.1',port: 9000,auth: {username: 'mikeymike',password: 'rapunz3l'}},// `cancelToken` specifies a cancel token that can be used to cancel the request// (see Cancellation section below for details)cancelToken: newCancelToken(function(cancel){}),// an alternative way to cancel Axios requests using AbortControllersignal: newAbortController().signal,// `decompress` indicates whether or not the response body should be decompressed // automatically. If set to `true` will also remove the 'content-encoding' header // from the responses objects of all decompressed responses// - Node only (XHR cannot turn off decompression)decompress: true// default// `insecureHTTPParser` boolean.// Indicates where to use an insecure HTTP parser that accepts invalid HTTP headers.// This may allow interoperability with non-conformant HTTP implementations.// Using the insecure parser should be avoided.// see options https://nodejs.org/dist/latest-v12.x/docs/api/http.html#http_http_request_url_options_callback// see also https://nodejs.org/en/blog/vulnerability/february-2020-security-releases/#strict-http-header-parsing-noneinsecureHTTPParser: undefined// default// transitional options for backward compatibility that may be removed in the newer versions transitional: {// silent JSON parsing mode// `true` - ignore JSON parsing errors and set response.data to null if parsing failed (old behaviour)// `false` - throw SyntaxError if JSON parsing failed (Note: responseType must be set to 'json')silentJSONParsing: true,// default value for the current Axios version// try to parse the response string as JSON even if `responseType` is not 'json'forcedJSONParsing: true,// throw ETIMEDOUT error instead of generic ECONNABORTED on request timeoutsclarifyTimeoutError: false,}}

Response Schema

The response for a request contains the following information.

{// `data` is the response that was provided by the serverdata: {},// `status` is the HTTP status code from the server responsestatus: 200,// `statusText` is the HTTP status message from the server responsestatusText: 'OK',// `headers` the HTTP headers that the server responded with// All header names are lower cased and can be accessed using the bracket notation.// Example: `response.headers['content-type']`headers: {},// `config` is the config that was provided to `axios` for the requestconfig: {},// `request` is the request that generated this response// It is the last ClientRequest instance in node.js (in redirects)// and an XMLHttpRequest instance in the browserrequest: {}}

When using , you will receive the response as follows:

axios.get('/user/12345').then(function(response){console.log(response.data);console.log(response.status);console.log(response.statusText);console.log(response.headers);console.log(response.config);});

When using , or passing a rejection callback as second parameter of , the response will be available through the object as explained in the Handling Errors section.

Config Defaults

You can specify config defaults that will be applied to every request.

Global axios defaults

axios.defaults.baseURL='https://api.example.com';// Important: If axios is used with multiple domains, the AUTH_TOKEN will be sent to all of them.// See below for an example using Custom instance defaults instead.axios.defaults.headers.common['Authorization']=AUTH_TOKEN;axios.defaults.headers.post['Content-Type']='application/x-www-form-urlencoded';

Custom instance defaults

// Set config defaults when creating the instanceconstinstance=axios.create({baseURL: 'https://api.example.com'});// Alter defaults after instance has been createdinstance.defaults.headers.common['Authorization']=AUTH_TOKEN;

Config order of precedence

Config will be merged with an order of precedence. The order is library defaults found in lib/defaults.js, then property of the instance, and finally argument for the request. The latter will take precedence over the former. Here's an example.

// Create an instance using the config defaults provided by the library// At this point the timeout config value is `0` as is the default for the libraryconstinstance=axios.create();// Override timeout default for the library// Now all requests using this instance will wait 2.5 seconds before timing outinstance.defaults.timeout=2500;// Override timeout for this request as it's known to take a long timeinstance.get('/longRequest',{timeout: 5000});

Interceptors

You can intercept requests or responses before they are handled by or .

// Add a request interceptoraxios.interceptors.request.use(function(config){// Do something before request is sentreturnconfig;},function(error){// Do something with request errorreturnPromise.reject(error);});// Add a response interceptoraxios.interceptors.response.use(function(response){// Any status code that lie within the range of 2xx cause this function to trigger// Do something with response datareturnresponse;},function(error){// Any status codes that falls outside the range of 2xx cause this function to trigger// Do something with response errorreturnPromise.reject(error);});

If you need to remove an interceptor later you can.

constmyInterceptor=axios.interceptors.request.use(function(){/*...*/});axios.interceptors.request.eject(myInterceptor);

You can add interceptors to a custom instance of axios.

constinstance=axios.create();instance.interceptors.request.use(function(){/*...*/});

When you add request interceptors, they are presumed to be asynchronous by default. This can cause a delay in the execution of your axios request when the main thread is blocked (a promise is created under the hood for the interceptor and your request gets put on the bottom of the call stack). If your request interceptors are synchronous you can add a flag to the options object that will tell axios to run the code synchronously and avoid any delays in request execution.

axios.interceptors.request.use(function(config){config.headers.test='I am only a header!';returnconfig;},null,{synchronous: true});

If you want to execute a particular interceptor based on a runtime check, you can add a function to the options object. The interceptor will not be executed if and only if the return of is . The function will be called with the config object (don't forget that you can bind your own arguments to it as well.) This can be handy when you have an asynchronous request interceptor that only needs to run at certain times.

functiononGetCall(config){returnconfig.method==='get';}axios.interceptors.request.use(function(config){config.headers.test='special get headers';returnconfig;},null,{runWhen: onGetCall});

Handling Errors

axios.get('/user/12345').catch(function(error){if(error.response){// The request was made and the server responded with a status code// that falls out of the range of 2xxconsole.log(error.response.data);console.log(error.response.status);console.log(error.response.headers);}elseif(error.request){// The request was made but no response was received// `error.request` is an instance of XMLHttpRequest in the browser and an instance of// http.ClientRequest in node.jsconsole.log(error.request);}else{// Something happened in setting up the request that triggered an Errorconsole.log('Error',error.message);}console.log(error.config);});

Using the config option, you can define HTTP code(s) that should throw an error.

axios.get('/user/12345',{validateStatus: function(status){returnstatus<500;// Resolve only if the status code is less than 500}})

Using you get an object with more information about the HTTP error.

axios.get('/user/12345').catch(function(error){console.log(error.toJSON());});

Cancellation

You can cancel a request using a cancel token.

The axios cancel token API is based on the withdrawn cancelable promises proposal.

You can create a cancel token using the factory as shown below:

constCancelToken=axios.CancelToken;constsource=CancelToken.source();axios.get('/user/12345',{cancelToken: source.token}).catch(function(thrown){if(axios.isCancel(thrown)){console.log('Request canceled',thrown.message);}else{// handle error}});axios.post('/user/12345',{name: 'new name'},{cancelToken: source.token})// cancel the request (the message parameter is optional)source.cancel('Operation canceled by the user.');

You can also create a cancel token by passing an executor function to the constructor:

constCancelToken=axios.CancelToken;letcancel;axios.get('/user/12345',{cancelToken: newCancelToken(functionexecutor(c){// An executor function receives a cancel function as a parametercancel=c;})});// cancel the requestcancel();

Axios supports AbortController to abort requests in way:

constcontroller=newAbortController();axios.get('/foo/bar',{signal: controller.signal}).then(function(response){//...});// cancel the requestcontroller.abort()

Note: you can cancel several requests with the same cancel token/abort controller. If a cancellation token is already cancelled at the moment of starting an Axios request, then the request is cancelled immediately, without any attempts to make real request.

Using application/x-www-form-urlencoded format

By default, axios serializes JavaScript objects to . To send data in the format instead, you can use one of the following options.

Browser

In a browser, you can use the API as follows:

constparams=newURLSearchParams();params.append('param1','value1');params.append('param2','value2');axios.post('/foo',params);

Note that is not supported by all browsers (see caniuse.com), but there is a polyfill available (make sure to polyfill the global environment).

Alternatively, you can encode data using the library:

constqs=require('qs');axios.post('/foo',qs.stringify({'bar': 123}));

Or in another way (ES6),

importqsfrom'qs';constdata={'bar': 123};constoptions={method: 'POST',headers: {'content-type': 'application/x-www-form-urlencoded'},data: qs.stringify(data), url,};axios(options);

Node.js

Query string

In node.js, you can use the module as follows:

constquerystring=require('querystring');axios.post('http://something.com/',querystring.stringify({foo: 'bar'}));

or 'URLSearchParams' from 'url module' as follows:

consturl=require('url');constparams=newurl.URLSearchParams({foo: 'bar'});axios.post('http://something.com/',params.toString());

You can also use the library.

NOTE

The library is preferable if you need to stringify nested objects, as the method has known issues with that use case (https://github.com/nodejs/node-v0.x-archive/issues/1665).

Form data

In node.js, you can use the library as follows:

constFormData=require('form-data');constform=newFormData();form.append('my_field','my value');form.append('my_buffer',newBuffer(10));form.append('my_file',fs.createReadStream('/foo/bar.jpg'));axios.post('https://example.com',form,{headers: form.getHeaders()})

Alternatively, use an interceptor:

axios.interceptors.request.use(config=>{if(config.datainstanceofFormData){Object.assign(config.headers,config.data.getHeaders());}returnconfig;});

Semver

Until axios reaches a release, breaking changes will be released with a new minor version. For example , and will have the same API, but will have breaking changes.

Promises

axios depends on a native ES6 Promise implementation to be supported. If your environment doesn't support ES6 Promises, you can polyfill.

TypeScript

axios includes TypeScript definitions and a type guard for axios errors.

letuser: User=null;try{const{ data }=awaitaxios.get('/user?ID=12345');user=data.userDetails;}catch(error){if(axios.isAxiosError(error)){handleAxiosError(error);}else{handleUnexpectedError(error);}}

Online one-click setup

You can use Gitpod an online IDE(which is free for Open Source) for contributing or running the examples online.

Open in Gitpod

Resources

Credits

axios is heavily inspired by the $http service provided in AngularJS. Ultimately axios is an effort to provide a standalone -like service for use outside of AngularJS.

License

MIT

Sours: https://www.npmjs.com/package/axios

Best JavaScript code snippets using axios(Showing top 15 results out of 15,732)

describe('functions_bearer_token', () => { it('should run', async () => { const {sample, mocks} = getSample(); await sample.callingFunction(null, mocks.res); assert(mocks.axios.get.calledTwice); assert.deepEqual(mocks.axios.get.firstCall.args[1], { headers: {'Metadata-Flavor': 'Google'}, }); assert(mocks.res.send.calledWith('function-response')); }); });
axios(apiEndpoint, fetchRequestConfig) .then(res => res.data) .catch(err => { console.error(`Unable to get content type (${resource}). Did you enable permissions in the Strapi admin for this?`) throw err })
async refreshAccessToken() { const { data } = awaitaxios({ baseURL: this.localApiUrl, url: '/api/v1/access_token', method: 'post', data: { refresh_token: this.session.getRefreshToken() } }); this.session.setAccessToken(data.access_token); }
asyncfunction request(options) { if (typeof options === 'string') { options = { url: options, }; } if (!options.method) { options.method = 'get'; } const result = awaitaxios(options); if (!result) { return undefined; } return result.data; }
async uploadFromStreamURL(url: string, pathname: string): Promise<string> { const client = new OSS({ region: this.configService.aliyunOSS.region, accessKeyId: this.configService.aliyunOSS.accessKeyID, accessKeySecret: this.configService.aliyunOSS.accessKeySecret, bucket: this.configService.aliyunOSS.bucket, }); const res = awaitaxios({ method: 'get', url, responseType: 'stream', }); const uploadName = `${this.configService.aliyunOSS.uploadPrefix}${pathname}`; const result = await client.putStream(uploadName, res.data.pipe(new PassThrough())); let name = result.name || ''; if (name.charAt(0) !== '/') { name = '/' + name; } returnthis.configService.static.uploadImgURL + name; }
async removeApp(appId, bundleId) { onlyForApps.call(this, 'Android'); if (wdioV4) { returnthis.browser.removeApp(bundleId); } returnaxios({ method: 'post', url: `${this._buildAppiumEndpoint()}/session/${this.browser.sessionId}/appium/device/remove_app`, data: { appId, bundleId }, }); }
async executeQuery(method, url, query, body, retryCount = 0) { if (retryCount > MAX_RETRY) { this.session.reset(); thrownew Error('MAX_RETRY_EXCEEDED'); } try { const { data } = awaitaxios({ baseURL: this.localApiUrl, url, method, params: query, data: body, headers: this.getAxiosHeaders() }); return data; } catch (e) { if (e.response && e.response.status === 401) { awaitthis.refreshAccessToken(); returnthis.executeQuery(method, url, query, body, retryCount + 1); } throw e; } }
async getIssues({ org, repo, labels, ignoreLabels = [] }) { const config = { method: 'POST', url: 'https://api.github.com/graphql', headers: { Authorization: `Bearer ${process.env.GitHubToken}`, 'Content-Type': 'application/json'} }; if (!!labels) { const issues = await labels.reduce(async (result, label) => { const query = this.getQuery(`repo:${org}/${repo} is:open is:issue label:${label} ${ignoreLabels.map(ignore => `-label:'${ignore}'`).join(' ')}`); const response = awaitaxios({...config, data: query }); if (response.data && response.data.errors && response.data.errors.length > 0) { this.context.error(JSON.stringify(response.data.errors, null, 2)); return; } const { data: { data: { search: { edges: issues }}}} = response; if (issues.length > 0) { result.push(issues); } return result; }, []); return issues; } else { const query = this.getQuery(`repo:${org}/${repo} is:issue ${ignoreLabels.map(ignore => `-label:${ignore}`).join(' ')}`); const { data: { data: { search: { edges: issues }}}} = awaitaxios({...config, data: query }); return issues; } }
response = awaitaxios(request); } catch (err) { if (!err.response) throw err;
response = awaitaxios(request); } catch (err) { if (!err.response) throw err;
async seeOrientationIs(orientation) { onlyForApps.call(this); let currentOrientation; if (wdioV4) { const res = awaitthis.browser.orientation(); currentOrientation = res; } const res = awaitaxios({ method: 'get', url: `${this._buildAppiumEndpoint()}/session/${this.browser.sessionId}/orientation`, }); currentOrientation = res.data.value; return truth('orientation', `to be ${orientation}`).assert(currentOrientation === orientation); }
async setOrientation(orientation) { onlyForApps.call(this); if (wdioV4) { returnthis.browser.setOrientation(orientation); } returnaxios({ method: 'post', url: `${this._buildAppiumEndpoint()}/session/${this.browser.sessionId}/orientation`, data: { orientation }, }); }
axios(apiEndpoint, fetchRequestConfig) .then(res => res.data) .catch(err => { console.error(`Unable to get content type (${resource}). Did you enable permissions in the Strapi admin for this?`) throw err })
async refreshAccessToken() { const { data } = awaitaxios({ baseURL: this.localApiUrl, url: '/api/v1/access_token', method: 'post', data: { refresh_token: this.session.getRefreshToken() } }); this.session.setAccessToken(data.access_token); }
async executeQuery(method, url, query, body, retryCount = 0) { if (retryCount > MAX_RETRY) { this.session.reset(); thrownew Error('MAX_RETRY_EXCEEDED'); } try { const { data } = awaitaxios({ baseURL: this.localApiUrl, url, method, params: query, data: body, headers: this.getAxiosHeaders() }); return data; } catch (e) { if (e.response && e.response.status === 401) { awaitthis.refreshAccessToken(); returnthis.executeQuery(method, url, query, body, retryCount + 1); } throw e; } }
Sours: https://www.tabnine.com/code/javascript/functions/axios
  1. Honda southern illinois
  2. Magnetic ear cuffs
  3. Kia sorrento reviews

How to use

request

function

in

axios

Best JavaScript code snippets using axios.request(Showing top 15 results out of 684)

instance.interceptors.request.use(async config => { if (config.url && config.url.charAt(0) === '/') { config.url = `${baseURL}${config.url}`; } config.headers.authorization = `Bearer ${getItem('token')}`; return config; }, error => Promise.reject(error));
axiosIntercept.interceptors.request.use( (config) => {
exportfunction getDocs () { returnrequest({ method: 'GET', url: '/docs' }) }
request(options) { returnthis.server.request({ method: options.method || 'GET', url: options.url, params: options.params || {}, data: options.data || {}, headers: extend({}, this.defaultHeaders(), options.headers || {}) }) .catch( (error) => { console.error("Error"); }); }
function goodInfo(goodId) { const stockLink = `http://item.jd.com/${goodId}.html`; returnrequest({ method: "get", url: stockLink, headers: Object.assign(defaultInfo.header, { cookie: defaultInfo.cookieData.join("") }), responseType: "arraybuffer" }); }
setupAxiosInterceptors(token) { axios.interceptors.request.use( (config) => { if (this.isUserLoggedIn()) { config.headers.authorization = token } return config } ) }
instance.interceptors.request.use(request => { console.log(request); return request; }, error => { console.log(error); return Promise.reject(error); });
const getPageHTML = async (url) => { try { returnawaitrequest(url) } catch (error) { console.error(error) } }
axios.interceptors.request.use(req => { return req }, err => { return Promise.reject(err.request) })
axios.interceptors.request.use(request => { if (accessToken) { request.headers.Authorization = `Bearer ${accessToken}`; } return request; });
axios.interceptors.request.use(function (config) { const token = localStorage.getItem('login_token'); if (token) { config.headers['x-access-token'] = token; } return config; }, function (error) { return Promise.reject(error); });
instance.interceptors.request.use(request => { return request; }, (error) => { return Promise.reject(error); });
instance.interceptors.request.use(async config => { if (config.url && config.url.charAt(0) === '/') { config.url = `${baseURL}${config.url}`; } config.headers.authorization = `Bearer ${getItem('token')}`; return config; }, error => Promise.reject(error));
setupAxiosInterceptors(token) { axios.interceptors.request.use( (config) => { if (this.isUserLoggedIn()) { config.headers.authorization = token } return config } ) }
instance.interceptors.request.use( async config => { const token = await AsyncStorage.getItem('token'); if (token) { config.headers.Authorization = `Bearer ${token}`; } return config; }, err => { return Promise.reject(err); } );
Sours: https://www.tabnine.com/code/javascript/functions/axios/request
How to make HTTP requests like a pro with Axios

Node.js Network Requests using Axios

In the modern technological world, it is very rare to find stand-alone applications. Most applications depend on resources from other applications. These resources are made available through the use of APIs. Servers are no exception. Though servers store their own relevant data, they sometimes need data from other servers. To access the data, servers need a way to communicate with the API(s) of the depended servers. This is where Axios comes in.

Introduction

Axios is a very popular JavaScript framework used to perform network requests. Axios works both on the browser and Node.js runtime. Axios is promise based but also allows the modern async/await methods. This article goes through Axios and how to use it to make network request in Node.js.

Prerequisites

To follow this article, you need to have Node.js installed and to understand the basics such as how to set up a simple server and to configure it. Go through this Node.js introduction article to get yourself up to speed.

Through this article, we are going to make network requests to a free JSON placeholder API from our Node.js application. Our application will be sending back the response it receives from the API.

Let’s get started!

Setting up our server

Start by creating a new Node.js project. Create a folder with the name of your choice and run the following commands from the terminal.

initializes a new node.js application whereas the second command installs and .

With that done, let’s go ahead and create our server.

Create an index.js file and write the following code in it.

Here, we import the required dependencies, i.e. express and axios. In the axios import, we use the create method to specify the base URL, this is the URL that our axios object will prepend to all our requests.

Run the server using this command.

Now that our server is up and running, let’s see what network requests are and what axios allows us to do.

Getting started with axios

We have mentioned network requests but we haven’t said what that is. As the name suggests, network requests are requests sent from a client to a server over the internet. The client in this case can also be another server. Axios allows us to make requests from both the browser and Node.js applications. It allows us to make both and requests which are the most used methods.

Let’s see how we can make these types of requests.

GET request

All axios requests are created using the axios object we imported in the first code snippet. The axios object takes an object parameter. The object contains the request URL and the HTTP method associated with the request.

Add the following code just before method.

In the above code, we have made an endpoint that makes a request to the JSON placeholder API. The endpoint then returns the response it receives from the server. The axios object returns a promise but we are able to use the async/await method which makes our code appear sequential. However, you can still use the promise library. This is how the code will look like.

Test the two endpoints using Postman and observe the output.

Alternatively, instead of writing the URL and the method, you can call the method directly from the object and just pass in the URL.

Example;

POST requests

For POST requests, the axios object takes in the URL, method and the body to POST.

To make a POST request, all you need to do is to call the POST method from the axios object and pass in the body to be posted.

Below is a code example using the async/await method.

When using promises, the code will be as follows:

Conclusion

This brings us to the end of our tutorial. In this article, we have gone through what axios is and how to use it to make GET and POST requests from Node.js. Axios also provides other HTTP requests such PUT and PATH but they are not very popular however, they use the same syntax as the two methods that we have gone through. Hope this helps you get started with axios.

Happy coding!


Peer Review Contributions by: Linus Muema


About the author

Peter Kayere

Peter Kayere is an undergraduate student at Jomo Kenyatta University of Agriculture and Technology studying Computer Technology. Peter has a great passion in software development particularly mobile web and android application development. Peter’s most used programming languages are Kotlin and Javascript.

Sours: https://www.section.io/engineering-education/nodejs-network-requests-using-axios/

Js axios

Axios tutorial

last modified July 23, 2021

Axios tutorial shows how to generage requests in JavaScript using Axios client library. Check the JavaScript fetch tutorial for an alternative way of creating requests in JavaScript.

Axios

is a promise based HTTP client for the browser and Node.js. Axios makes it easy to send asynchronous HTTP requests to REST endpoints and perform CRUD operations. It can be used in plain JavaScript or with a library such as Vue or React.

In this tutorial we work with Axios in a Node.js application.

Setting up Axios

First, we install Axios.

$ node -v v12.20.1

We use Node.js version 12.20.1.

$ npm init -y

We initiate a new Node.js application.

$ npm i axios

We install Axios with command.

Axios making requests

There are multiple methods for creating requests in axios.

axios(config) axios(url[, config])

These are basic methods for generating requests in axios.

axios.request(config) axios.get(url[, config]) axios.delete(url[, config]) axios.head(url[, config]) axios.options(url[, config]) axios.post(url[, data[, config]]) axios.put(url[, data[, config]]) axios.patch(url[, data[, config]])

These are method aliases, created for convenience.

Axios Response object

When we send a request to a server, it returns a response. The Axios response object consists of:

  • data - the payload returned from the server
  • status - the HTTP code returned from the server
  • statusText - the HTTP status message returned by the server
  • headers - headers sent by server
  • config - the original request configuration
  • request - the request object

Axios GET request with callbacks

In the first example, we create a simple GET request. We use callbacks.

get_req.js

const axios = require('axios'); axios.get('http://webcode.me').then(resp => { console.log(resp.data); });

We generate a simple GET request and show the output.

const axios = require('axios');

The Axios library is included.

axios.get('http://webcode.me').then(resp => { console.log(resp.data); });

With , we send a GET request. We output the data from the response. The data is HTML code.

$ node get_req.js <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>My html page</title> </head> <body> <p> Today is a beautiful day. We go swimming and fishing. </p> <p> Hello there. How are you? </p> </body> </html>

Axios GET request with async/await

The following example creates the same request. This time we use syntax.

get_req_async.js

const axios = require('axios'); async function makeGetRequest() { let res = await axios.get('http://webcode.me'); let data = res.data; console.log(data); } makeGetRequest();

The example creates a simple GET request utilizing syntax.

Axios basic API

The , , or methods are convenience methods for the basic axios API: and .

basic_api.js

const axios = require('axios'); async function makeRequest() { const config = { method: 'get', url: 'http://webcode.me' } let res = await axios(config) console.log(res.status); } makeRequest();

The example creates a GET request to .

const config = { method: 'get', url: 'http://webcode.me' }

We specify the details of the request in the configuration object.

Axios HEAD request

A HEAD request is a GET request without a message body. In Axios, a HEAD request is created with .

head_req.js

const axios = require('axios'); async function makeHeadRequest() { let res = await axios.head('http://webcode.me'); console.log(`Status: ${res.status}`) console.log(`Server: ${res.headers.server}`) console.log(`Date: ${res.headers.date}`) } makeHeadRequest();

The example shows the status, server name, response date from a response generated with a HEAD request.

$ node head_req.js Status: 200 Server: nginx/1.6.2 Date: Wed, 10 Feb 2021 09:52:59 GMT

Axios status code

HTTP response status codes indicate whether a specific HTTP request has been successfully completed. Responses are grouped in five classes:

  • Informational responses (100–199)
  • Successful responses (200–299)
  • Redirects (300–399)
  • Client errors (400–499)
  • Server errors (500–599)

status_code.js

const axios = require('axios'); async function makeRequest() { const config = { method: 'head', url: 'http://webcode.me' } let res = await axios(config) console.log(res.status); } makeRequest();

We get the status code from the property of the response.

$ node status_code.js 200

Axios custom header

In the following example, we send a custom header.

custom_header.js

const axios = require('axios'); async function makeRequest() { const config = { method: 'get', url: 'http://webcode.me', headers: { 'User-Agent': 'Axios - console app' } } let res = await axios(config) console.log(res.request._header); } makeRequest();

The example sends a customized header.

const config = { method: 'get', url: 'http://webcode.me', headers: { 'User-Agent': 'Axios- console app' } }

The custom data is added to the attribute of the configuration object.

console.log(res.request._header);

We verify the sent data.

$ node custom_header.js GET / HTTP/1.1 Accept: application/json, text/plain, */* User-Agent: Console app Host: webcode.me Connection: close

Axios GET request query parameters

In the following example, we append some query parameters to the URL.

get_req_query.js

const axios = require('axios'); const url = require('url'); async function makeGetRequest() { let payload = { name: 'John Doe', occupation: 'gardener' }; const params = new url.URLSearchParams(payload); let res = await axios.get(`http://httpbin.org/get?${params}`); let data = res.data; console.log(data); } makeGetRequest();

We use the of the module to transform the JSON object into suitable URL query form.

$ node get_req_query.js { args: { name: 'John Doe', occupation: 'gardener' }, headers: { Accept: 'application/json, text/plain, */*', Host: 'httpbin.org', 'User-Agent': 'axios/0.21.1', 'X-Amzn-Trace-Id': 'Root=1-6023ba22-48b1ff807ea9d934457abbcd' }, ... url: 'http://httpbin.org/get?name=John+Doe&occupation=gardener' }

Getting Github information

Many online services contain public APIs. In the following example, we generate a request to a Github API.

github_info.js

const axios = require('axios'); async function getNumberOfFollowers() { let res = await axios.get('https://api.github.com/users/janbodnar'); let nOfFollowers = res.data.followers; let location = res.data.location; console.log(`# of followers: ${nOfFollowers}`) console.log(`Location: ${location}`) } getNumberOfFollowers();

In the example, we get the number of followers and location of a user.

$ node github_info.js # of followers: 195 Location: Bratislava

Axios POST JSON request

A POST request is created with method.

Axios automatically serializes JavaScript objects to JSON when passed to the function as the second parameter; we do not need to serialize POST bodies to JSON.

post_json.js

const axios = require('axios'); async function makeGetRequest() { let payload = { name: 'John Doe', occupation: 'gardener' }; let res = await axios.post('http://httpbin.org/post', payload); let data = res.data; console.log(data); } makeGetRequest();

The example creates a POST request to an online testing service. The payload is the second parameter to the function.

$ node post_json.js { args: {}, data: '{"name":"John Doe","occupation":"gardener"}', files: {}, form: {}, headers: { Accept: 'application/json, text/plain, */*', 'Content-Length': '43', 'Content-Type': 'application/json;charset=utf-8', Host: 'httpbin.org', 'User-Agent': 'axios/0.21.1', 'X-Amzn-Trace-Id': 'Root=1-6023bc92-5bcf8f4e10f829be3a3f04f7' }, json: { name: 'John Doe', occupation: 'gardener' }, ... url: 'http://httpbin.org/post' }

Axios POST FORM request

In the following example, we generate a POST request with form data.

$ npm i form-data

We install the module.

With application/x-www-form-urlencoded the data is sent in the body of the request; the keys and values are encoded in key-value tuples separated by '&', with a '=' between the key and the value.

post_form.js

const axios = require('axios'); const FormData = require('form-data'); async function makeGetRequest() { const form_data = new FormData(); form_data.append('name', 'John Doe'); form_data.append('occupation', 'gardener'); let res = await axios.post('http://httpbin.org/post', form_data, { headers: form_data.getHeaders() }); let data = res.data; console.log(data); } makeGetRequest();

To produce form data in the appropriate format, we use the FormData object.

$ node post_form.js { args: {}, data: '', files: {}, form: { name: 'John Doe', occupation: 'gardener' }, headers: { Accept: 'application/json, text/plain, */*', 'Content-Length': '284', 'Content-Type': 'multipart/form-data; ... Host: 'httpbin.org', 'User-Agent': 'axios/0.21.1', 'X-Amzn-Trace-Id': 'Root=1-6023bff5-056fc9fd39f94e870b52169b' }, json: null, ... url: 'http://httpbin.org/post' }

Axios download image

The following example shows how to download an image with Axios.

get_image.js

const axios = require('axios'); const fs = require('fs'); var config = { responseType: 'stream' }; let url = 'https://images.dog.ceo/breeds/setter-english/n02100735_4870.jpg'; async function getImage() { let resp = await axios.get(url, config); resp.data.pipe(fs.createWriteStream('image.jpg')); } getImage();

The example retrieves an image from an online service, which keeps images of dogs.

const axios = require('axios'); const fs = require('fs');

We include and modules.

var config = { responseType: 'stream' };

We specify the response type in the configuration object.

let resp = await axios.get(url, config);

We get the image.

resp.data.pipe(fs.createWriteStream('image.jpg'));

With the help of the module, we save the image to disk.

Axios multiple requests

We can create multiple requests in one shot with Axios.

multiple_requests.js

const axios = require('axios'); async function makeRequests(urls) { const fetchUrl = (url) => axios.get(url); const promises = urls.map(fetchUrl); let responses = await Promise.all(promises); responses.forEach(resp => { let msg = `${resp.config.url} -> ${resp.headers.server}: ${resp.status}`; console.log(msg); }); } let urls = [ 'http://webcode.me', 'https://example.com', 'http://httpbin.org', 'https://clojure.org', 'https://fsharp.org', 'https://symfony.com', 'https://www.perl.org', 'https://www.php.net', 'https://www.python.org', 'https://code.visualstudio.com', 'https://github.com' ]; makeRequests(urls);

The example generates async requests to the given list of urls. It prints the web site's url, server name, and status code.

const fetchUrl = (url) => axios.get(url);

The makes an async request and returns a promise.

let responses = await Promise.all(promises);

We collect all promises with . The method resolves after all of the given promises have either fulfilled or rejected.

$ node multiple_requests.js http://webcode.me -> nginx/1.6.2: 200 https://example.com -> ECS (dcb/7F83): 200 http://httpbin.org -> gunicorn/19.9.0: 200 https://clojure.org -> AmazonS3: 200 https://fsharp.org -> GitHub.com: 200 https://symfony.com -> cloudflare: 200 https://www.perl.org -> Combust/Plack (Perl): 200 https://www.php.net -> myracloud: 200 https://www.python.org -> nginx: 200 https://code.visualstudio.com -> Microsoft-IIS/10.0: 200 https://github.com -> GitHub.com: 200

Using Axios with JSON Server

JSON Server is a wonderful tool, which allows us to create fake REST APIs easily.

$ npm i -g json-server

We install .

users.json

{ "users": [ { "id": 1, "first_name": "Robert", "last_name": "Schwartz", "email": "[email protected]" }, { "id": 2, "first_name": "Lucy", "last_name": "Ballmer", "email": "[email protected]" }, { "id": 3, "first_name": "Anna", "last_name": "Smith", "email": "[email protected]" }, { "id": 4, "first_name": "Robert", "last_name": "Brown", "email": "[email protected]" }, { "id": 5, "first_name": "Roger", "last_name": "Bacon", "email": "[email protected]" } ] }

This is our test data.

Starting JSON server

The JSON server is started with the json-server, which we have installed globally.

$ json-server --watch users.json

The option is used to specify the data for the server.

$ curl localhost:3000/users/2/ { "id": 2, "first_name": "Lucy", "last_name": "Ballmer", "email": "[email protected]" }

With the curl command, we get the user with Id 2.

Posting a user

We post a new user.

post_user.js

const axios = require('axios'); async function makePostRequest() { params = { id: 6, first_name: 'Fred', last_name: 'Blair', email: '[email protected]' } let res = await axios.post('http://localhost:3000/users/', params); console.log(res.data); } makePostRequest();

The example posts a new user.

let res = await axios.post('http://localhost:3000/users/', params);

The post parameters are passed as the second parameter to the method.

Getting users

We get users from the test server.

get_users.js

const axios = require('axios'); async function makeGetRequest() { let res = await axios.get('http://localhost:3000/users/'); let data = res.data; console.log(data); } makeGetRequest();

This program retrieves all users from our test server.

$ node get_users.js [ { id: 1, first_name: 'Robert', last_name: 'Schwartz', email: '[email protected]' }, { id: 2, first_name: 'Lucy', last_name: 'Ballmer', email: '[email protected]' }, { id: 3, first_name: 'Anna', last_name: 'Smith', email: '[email protected]' }, { id: 4, first_name: 'Robert', last_name: 'Brown', email: '[email protected]' }, { id: 5, first_name: 'Roger', last_name: 'Bacon', email: '[email protected]' }, { id: 6, first_name: 'Fred', last_name: 'Blair', email: '[email protected]' } ]

Deleting a user

A resource is deleted with .

delete_user.js

const axios = require('axios'); async function makePostRequest() { let res = await axios.delete('http://localhost:3000/users/2/'); console.log(res.status); } makePostRequest();

The example deletes the user with Id 2.

In this tutorial, we have worked with JavaScript Axios module.

List all JavaScript tutorials.

Sours: https://zetcode.com/javascript/axios/
Axios Crash Course - HTTP Library

Axios Tutorial: Get/Post/Put/Delete request example

Axios is a promise-based HTTP Client Javascript library for Node.js and Browser. In this tutorial, we will create examples that use Axios to make Get/Post/Put/Delete request. The final section shows a simple Axios HTTP Client to interact with Rest API.

Related Posts:
– Axios Interceptors tutorial with Refresh Token example
– Javascript Fetch API tutorial: Get/Post/Put/Delete example

Contents

Axios Features

Axios can run in the Node.js and Browser with the same codebase.
– On the server-side it uses the native Node.js module
– On the client-side (browser) it uses

Additionally, there are important features that you should know:

  • Supports the Promise API
  • Intercept request and response (Axios Interceptors tutorial)
  • Transform request and response data
  • Cancel requests
  • Automatic transforms for JSON data
  • Client side support for protecting against XSRF

(from https://github.com/axios/axios#features)

Install Axios

We can add Axios to our project/code with one of following simple ways:

– npm:

– bower:

– yarn:

– CDN:

Or:

Axios Response Object schema

The response for a Axios request contains:

  • : parsed response body provided by the server
  • : HTTP status code
  • : HTTP status message
  • : HTTP headers (lower case)
  • : the request config that was provided to
  • : the last client request instance that generated this response

For example:

Axios Response Body

Axios Response Object has field that contains the parsed response body.
We can use or await to receive the response body as follows:

Axios Error handling

We use for handling errors.

Axios Error handling with async-await

If you want to use async-await, just wrap the axios call with try/catch block.

Axios GET request

Async/await:

Axios GET with params

You can use the config option to set query string params.

And this is equivalent:

Axios GET with headers

To send Axios GET request with Headers, we pass an option object with property.

Axios GET with params and headers

We can merge and in a Axios GET request like this.

Axios POST with body

You can perform an Axios POST object request with as second parameter.

Axios POST with headers

To send Axios POST request with Headers, we pass an option object with property right after the .

Axios PUT request

You can perform an Axios PUT json object request with as second parameter.

Axios PUT with headers

To send Axios PUT request with Headers, we pass an option object with property right after the .

Axios DELETE request

Axios DELETE with headers

To send Axios DELETE request with Headers, we pass an option object with property.

Create Axios instance

We can create a new instance of axios using method.

Axios Request example with Rest API

We will build a HTTP Client to make CRUD requests to Rest API in that:

  • Axios GET request: get all Tutorials, get Tutorial by Id, find Tutorial by title
  • Axios POST request: create new Tutorial
  • Axios PUT request: update an existing Tutorial
  • Axios DELETE request: delete a Tutorial, delete all Tutorials

axios-request-example-get-post-put-delete

This Axios Client works with the following Web API:

MethodsUrlsActions
POST/api/tutorialscreate new Tutorial
GET/api/tutorialsretrieve all Tutorials
GET/api/tutorials/:idretrieve a Tutorial by
PUT/api/tutorials/:idupdate a Tutorial by
DELETE/api/tutorials/:iddelete a Tutorial by
DELETE/api/tutorialsdelete all Tutorials
GET/api/tutorials?title=[keyword]find all Tutorials which title contains

You can find step by step to build a Server like this in one of these posts:

Remember that you need to configure CORS: .
It helps the REST APIs can be accessed by any origin.

– Create a Tutorial using axios POST request:

axios-post-request-example

– Retrieve all Tutorials using axios GET request:

axios-get-request-example

– Retrieve a Tutorial by Id using axios GET request:

axios-get-request-example-by-id

– Find Tutorials by title using axios GET request with params:

axios-get-request-params-example

– Update a Tutorial using axios PUT request:

axios-put-request-example

– Delete Tutorial using axios DELETE request:

axios-delete-request-example

Source Code

index.html

main.js

Conclusion

With this Axios tutorial, you’ve known many ways to make GET/POST/PUT/DELETE request using Axios (with headers, params, body…). Furthermore, you can apply it in one of following React/Vue applications:

If you want to use Fetch API instead, please visit:
Javascript Fetch API tutorial: Get/ Post/ Put/ Delete example

Happy Learning! See you again.

Further Reading

Sours: https://www.bezkoder.com/axios-request/

You will also like:

How to make HTTP requests with Axios

Editor’s note: This Axios tutorial was last updated on 26 January 2021.

Axios is a client HTTP API based on the interface provided by browsers.

In this tutorial, we’ll demonstrate how to make HTTP requests using Axios with clear examples, including how to make an Axios POST request with , how to send multiple requests simultaneously with , and much more.

We’ll cover the following in detail:

If you’re more of a visual learner, check out the video tutorial below:

Why use Axios?

The most common way for frontend programs to communicate with servers is through the HTTP protocol. You are probably familiar with the Fetch API and the interface, which allows you to fetch resources and make HTTP requests.

If you’re using a JavaScript library, chances are it comes with a client HTTP API. jQuery’s function, for example, has been particularly popular with frontend developers. But as developers move away from such libraries in favor of native APIs, dedicated HTTP clients have emerged to fill the gap.

As with Fetch, Axios is promise-based. However, it provides a more powerful and flexible feature set.

Advantages of using Axios over the native Fetch API include:

  • Request and response interception
  • Streamlined error handling
  • Protection against XSRF
  • Support for upload progress
  • Response timeout
  • The ability to cancel requests
  • Support for older browsers
  • Automatic JSON data transformation

Installing Axios

You can install Axios using:

  • npm: $ npm install axios
  • The Bower package manager: $ bower install axios
  • Or a content delivery network: <script src="https://unpkg.com/axios/dist/axios.min.js"></script>

How to make an Axios POST request

Making an HTTP request is as easy as passing a config object to the Axios function. You can make a POST request using Axios to “post” data to a given endpoint and trigger events.

To perform an HTTP POST request in Axios, call .

Making a POST request in Axios requires two parameters: the URI of the service endpoint and an object that contains the properties you wish to send to the server.

For a simple Axios POST request, the object must have a property. If no method is provided, will be used as the default value.

Let’s look at a simple Axios POST example:

// send a POST request axios({ method: 'post', url: '/login', data: { firstName: 'Finn', lastName: 'Williams' } });

This should look familiar to those who have worked with jQuery’s function. This code is simply instructing Axios to send a POST request to with an object of key/value pairs as its data. Axios will automatically convert the data to JSON and send it as the request body.

Shorthand methods for Axios HTTP requests

Axios also provides a set of shorthand methods for performing different types of requests. The methods are as follows:

    For instance, the following code shows how the previous example could be written using the method:

    axios.post('/login', { firstName: 'Finn', lastName: 'Williams' });

    What does return?

    Once an HTTP POST request is made, Axios returns a promise that is either fulfilled or rejected, depending on the response from the backend service.

    To handle the result, you can use the method, like this:

    axios.post('/login', { firstName: 'Finn', lastName: 'Williams' }) .then((response) => { console.log(response); }, (error) => { console.log(error); });

    If the promise is fulfilled, the first argument of will be called; if the promise is rejected, the second argument will be called. According to the documentation, the fulfillment value is an object containing the following information:

    { // `data` is the response that was provided by the server data: {}, // `status` is the HTTP status code from the server response status: 200, // `statusText` is the HTTP status message from the server response statusText: 'OK', // `headers` the headers that the server responded with // All header names are lower cased headers: {}, // `config` is the config that was provided to `axios` for the request config: {}, // `request` is the request that generated this response // It is the last ClientRequest instance in node.js (in redirects) // and an XMLHttpRequest instance the browser request: {} }

    As an example, here’s how the response looks when requesting data from the GitHub API:

    axios.get('https://api.github.com/users/mapbox') .then((response) => { console.log(response.data); console.log(response.status); console.log(response.statusText); console.log(response.headers); console.log(response.config); }); // logs: // => {login: "mapbox", id: 600935, node_id: "MDEyOk9yZ2FuaXphdGlvbjYwMDkzNQ==", avatar_url: "https://avatars1.githubusercontent.com/u/600935?v=4", gravatar_id: "", …} // => 200 // => OK // => {x-ratelimit-limit: "60", x-github-media-type: "github.v3", x-ratelimit-remaining: "60", last-modified: "Wed, 01 Aug 2018 02:50:03 GMT", etag: "W/"3062389570cc468e0b474db27046e8c9"", …} // => {adapter: ƒ, transformRequest: {…}, transformResponse: {…}, timeout: 0, xsrfCookieName: "XSRF-TOKEN", …}

    Using to send multiple requests

    One of Axios’ more interesting features is its ability to make multiple requests in parallel by passing an array of arguments to the method. This method returns a single promise object that resolves only when all arguments passed as an array have resolved.

    Here’s a simple example of how to use to make simultaneous HTTP requests:

    // execute simultaneous requests axios.all([ axios.get('https://api.github.com/users/mapbox'), axios.get('https://api.github.com/users/phantomjs') ]) .then(responseArr => { //this will be executed only when all requests are complete console.log('Date created: ', responseArr[0].data.created_at); console.log('Date created: ', responseArr[1].data.created_at); }); // logs: // => Date created: 2011-02-04T19:02:13Z // => Date created: 2017-04-03T17:25:46Z

    This code makes two requests to the GitHub API and then logs the value of the property of each response to the console. Keep in mind that if any of the arguments rejects then the promise will immediately reject with the reason of the first promise that rejects.

    For convenience, Axios also provides a method called to assign the properties of the response array to separate variables. Here’s how you could use this method:

    axios.all([ axios.get('https://api.github.com/users/mapbox'), axios.get('https://api.github.com/users/phantomjs') ]) .then(axios.spread((user1, user2) => { console.log('Date created: ', user1.data.created_at); console.log('Date created: ', user2.data.created_at); })); // logs: // => Date created: 2011-02-04T19:02:13Z // => Date created: 2017-04-03T17:25:46Z

    The output of this code is the same as the previous example. The only difference is that the method is used to unpack values from the response array.

    Sending custom headers with Axios is very straightforward. Simply pass an object containing the headers as the last argument. For example:

    const options = { headers: {'X-Custom-Header': 'value'} }; axios.post('/save', { a: 10 }, options);

    POST JSON with Axios

    Axios automatically serializes JavaScript objects to JSON when passed to the function as the second parameter. This eliminates the need to serialize POST bodies to JSON.

    Axios also sets the header to . This enables web frameworks to automatically parse the data.

    If you want to send a preserialized JSON string to as JSON, you’ll need to make sure the header is set.

    Transforming requests and responses

    Although Axios automatically converts requests and responses to JSON by default, it also allows you to override the default behavior and define a different transformation mechanism. This is particularly useful when working with an API that accepts only a specific data format, such as XML or CSV.

    To change request data before sending it to the server, set the property in the config object. Note that this method only works for , , and request methods.

    Here’s an example of how to use in Axios:

    const options = { method: 'post', url: '/login', data: { firstName: 'Finn', lastName: 'Williams' }, transformRequest: [(data, headers) => { // transform the data return data; }] }; // send the request axios(options);

    To modify the data before passing it to or , you can set the property:

    const options = { method: 'post', url: '/login', data: { firstName: 'Finn', lastName: 'Williams' }, transformResponse: [(data) => { // transform the response return data; }] }; // send the request axios(options);

    Intercepting requests and responses

    HTTP interception is a popular feature of Axios. With this feature, you can examine and change HTTP requests from your program to the server and vice versa, which is very useful for a variety of implicit tasks, such as logging and authentication.

    At first glance, interceptors look very much like transforms, but they differ in one key way: unlike transforms, which only receive the data and headers as arguments, interceptors receive the entire response object or request config.

    You can declare a request interceptor in Axios like this:

    // declare a request interceptor axios.interceptors.request.use(config => { // perform a task before the request is sent console.log('Request was sent'); return config; }, error => { // handle the error return Promise.reject(error); }); // sent a GET request axios.get('https://api.github.com/users/mapbox') .then(response => { console.log(response.data.created_at); });

    This code logs a message to the console whenever a request is sent then waits until it gets a response from the server, at which point it prints the time the account was created at GitHub to the console. One advantage of using interceptors is that you no longer have to implement tasks for each HTTP request separately.

    Axios also provides a response interceptor, which allows you to transform the responses from a server on their way back to the application:

    // declare a response interceptor axios.interceptors.response.use((response) => { // do something with the response data console.log('Response was received'); return response; }, error => { // handle the response error return Promise.reject(error); }); // sent a GET request axios.get('https://api.github.com/users/mapbox') .then(response => { console.log(response.data.created_at); });

    Client-side support for protection against XSRF

    Cross-site request forgery (or XSRF for short) is a method of attacking a web-hosted app in which the attacker disguises himself as a legal and trusted user to influence the interaction between the app and the user’s browser. There are many ways to execute such an attack, including .

    Fortunately, Axios is designed to protect against XSRF by allowing you to embed additional authentication data when making requests. This enables the server to discover requests from unauthorized locations. Here’s how this can be done with Axios:

    const options = { method: 'post', url: '/login', xsrfCookieName: 'XSRF-TOKEN', xsrfHeaderName: 'X-XSRF-TOKEN', }; // send the request axios(options);

    200’s only Monitor failed and slow Axios requests in production

    While Axios has some features for debugging requests and responses, making sure Axios continues to serve resources to your app in production is where things get tougher. If you’re interested in ensuring requests to the backend or 3rd party services are successful, try LogRocket. LogRocket Dashboard Free Trial Banner.https://logrocket.com/signup/

    LogRocket is like a DVR for web apps, recording literally everything that happens on your site. Instead of guessing why problems happen, you can aggregate and report on problematic Axios requests to quickly understand the root cause.

    LogRocket instruments your app to record baseline performance timings such as page load time, time to first byte, and slow network requests as well as logs Redux, NgRx. and Vuex actions/state. Start monitoring for free.

    Monitoring POST request progress

    Another interesting feature of Axios is the ability to monitor request progress. This is especially useful when downloading or uploading large files. The provided example in the Axios documentation gives you a good idea of how that can be done. But for the sake of simplicity and style, we are going to use the Axios Progress Bar module in this tutorial.

    The first thing we need to do to use this module is to include the related style and script:

    <link rel="stylesheet" type="text/css" href="https://cdn.rawgit.com/rikmms/progress-bar-4-axios/0a3acf92/dist/nprogress.css" /> <script src="https://cdn.rawgit.com/rikmms/progress-bar-4-axios/0a3acf92/dist/index.js"></script>

    Then we can implement the progress bar like this:

    loadProgressBar() const url = 'https://media.giphy.com/media/C6JQPEUsZUyVq/giphy.gif'; function downloadFile(url) { axios.get(url) .then(response => { console.log(response) }) .catch(error => { console.log(error) }) } downloadFile(url);

    To change the default styling of the progress bar, we can override the following style rules:

    #nprogress .bar { background: red !important; } #nprogress .peg { box-shadow: 0 0 10px red, 0 0 5px red !important; } #nprogress .spinner-icon { border-top-color: red !important; border-left-color: red !important; }

    Canceling requests

    In some situations, you may no longer care about the result and want to cancel a request that’s already sent. This can be done by using a cancel token. The ability to cancel requests was added to Axios in version 1.5 and is based on the cancelable promises proposal. Here’s a simple example:

    const source = axios.CancelToken.source(); axios.get('https://media.giphy.com/media/C6JQPEUsZUyVq/giphy.gif', { cancelToken: source.token }).catch(thrown => { if (axios.isCancel(thrown)) { console.log(thrown.message); } else { // handle error } }); // cancel the request (the message parameter is optional) source.cancel('Request canceled.');

    You can also create a cancel token by passing an executor function to the constructor, as shown below:

    const CancelToken = axios.CancelToken; let cancel; axios.get('https://media.giphy.com/media/C6JQPEUsZUyVq/giphy.gif', { // specify a cancel token cancelToken: new CancelToken(c => { // this function will receive a cancel function as a parameter cancel = c; }) }).catch(thrown => { if (axios.isCancel(thrown)) { console.log(thrown.message); } else { // handle error } }); // cancel the request cancel('Request canceled.');

    Popular Axios libraries

    Axios’ rise in popularity among developers has resulted in a rich selection of third-party libraries that extend its functionality. From testers to loggers, there’s a library for almost any additional feature you may need when using Axios. Here are some popular libraries currently available:

    Browser support

    When it comes to browser support, Axios is very reliable. Even older browsers such as IE 11 work well with Axios.

    Chrome

    Firefox

    Safari

    Edge

    IE

    heavy check mark
    heavy check mark
    heavy check mark
    heavy check mark

    11

    Wrapping up

    There’s a good reason Axios is so popular among developers: it’s packed with useful features. In this post, we’ve taken a good look at several key features of Axios and learned how to use them in practice. But there are still many aspects of Axios that we’ve not discussed. So be sure to check out the Axios GitHub page to learn more.

    Do you have some tips on using Axios? Let us know in the comments!

    Sours: https://blog.logrocket.com/how-to-make-http-requests-like-a-pro-with-axios/


    1181 1182 1183 1184 1185