Axios response status

Axios response status DEFAULT

Axios tutorial

last modified July 23,

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 v

We use Node.js version

$ 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="> <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: Server: nginx/ Date: Wed, 10 Feb 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 (–)
  • Successful responses (–)
  • Redirects (–)
  • Client errors (–)
  • Server errors (–)

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

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/ 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/', 'X-Amzn-Trace-Id': 'Root=bab1ffea9dabbcd' }, 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: 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/', 'X-Amzn-Trace-Id': 'Root=bcbcf8f4e10fbe3a3f04f7' }, 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': '', 'Content-Type': 'multipart/form-data; Host: 'httpbin.org', 'User-Agent': 'axios/', 'X-Amzn-Trace-Id': 'Root=bfffc9fd39f94ebb' }, 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/n_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/ https://example.com -> ECS (dcb/7F83): http://httpbin.org -> gunicorn/ https://clojure.org -> AmazonS3: https://fsharp.org -> GitHub.com: https://symfony.com -> cloudflare: https://www.perl.org -> Combust/Plack (Perl): https://www.php.net -> myracloud: https://www.python.org -> nginx: https://code.visualstudio.com -> Microsoft-IIS/ https://github.com -> GitHub.com:

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/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/users/', params); console.log(res.data); } makePostRequest();

The example posts a new user.

let res = await axios.post('http://localhost/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/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/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/

Best JavaScript code snippets using axios.AxiosResponse.status(Showing top 15 results out of )

instance.interceptors.response.use(response => { if (response.status === ) { return response; } return Promise.reject(response); }, error => { if (error) { let msg = ''; if (error.response && error.response.status === ) { msg = error.response.data.msg; return; } msg = '网络异常,请检查你的网络。'; Toast({ content: msg, timeout: , background: "#f" }); } else { Toast({ content: '未知错误。', timeout: , background: "#f" }); } return Promise.reject(error); });
}); if (!(result.status === && !result.data.error)) { res.status(); res.redirect('/signup'); return; }); if (!(userResult.status === && !userResult.data.error)) { res.status(); res.redirect('/signup'); return; res.status(); res.redirect('/');
})) .then(response => { if (response.status === ) { dispatch({ type: SUBSCRIPTIONS_GET_LIST_RESPONSE,
const result = await axios.post(util.format(accessTokenURL, appKey, appSecret, redirectURL, code)); if (!(result.status === && result.data.access_token)) { res.status(); res.redirect('/signup'); return; const userResult = await axios.get(userInfoURL); if (!(userResult.status === && userResult.data.id)) { res.status(); res.redirect('/signup'); return; res.status(); res.redirect('/');
})) .then(response => { if (response.status === ) { dispatch({ type: PRODUCTS_GET_RELATED_LIST_RESPONSE,
})) .then(response => { if (response.status === ) { if (response.data.errors && response.data.errors.length > 0) { dispatch({
})) .then(response => { if (response.status === ) { dispatch({ type: PRODUCTS_GET_LIST_RESPONSE,
})) .then(response => { if (response.status === ) { dispatch({ type: SUBSCRIPTIONS_GET_LIST_BY_USER_RESPONSE,
})) .then(response => { if (response.status === ) { dispatch({ type: CRATES_GET_LIST_RESPONSE,
instance.interceptors.response.use(response => { if (response.status === ) { return response; } return Promise.reject(response); }, error => { if (error) { let msg = ''; if (error.response && error.response.status === ) { msg = error.response.data.msg; return; } msg = '网络异常,请检查你的网络。'; Toast({ content: msg, timeout: , background: "#f" }); } else { Toast({ content: '未知错误。', timeout: , background: "#f" }); } return Promise.reject(error); });
})) .then(response => { if (response.status === ) { dispatch({ type: SUBSCRIPTIONS_GET_LIST_RESPONSE,
})) .then(response => { if (response.status === ) { dispatch({ type: SUBSCRIPTIONS_GET_LIST_BY_USER_RESPONSE,
})) .then(response => { if (response.status === ) { dispatch({ type: CRATES_GET_LIST_RESPONSE,
})) .then(response => { if (response.status === ) { dispatch({ type: PRODUCTS_GET_LIST_RESPONSE,
})) .then(response => { if (response.status === ) { dispatch({ type: PRODUCTS_GET_RELATED_LIST_RESPONSE,
Sours: https://www.tabnine.com/code/javascript/functions/axios/AxiosResponse/status
  1. Restaurants in leadville colorado
  2. Wedding dress types quiz
  3. 8 inch plate hanger
  4. 2020 news cast
  5. Protech rockeye

Get the HTTP Response Body with Axios

Jul 23,

When you on an Axios request, you get back an Axios response. An Axios response is a POJO with several properties, including , which contains the parsed response body.

An Axios response contains several other properties, like , which contains the HTTP response status code (like or ). But most of the time you don't care about the response code if the request succeeded, so you will often see code that gets the response body directly using promise chaining.

You can also get the response body using destructuring assignments.

Automatic Parsing

Axios parses the response based on the HTTP response's header. When the response's content type is , Axios will automatically try to parse the response into a JavaScript object.

Keep in mind that the response headers are sent by the server. So if the server sends back a different content type, you may need to handle it the response yourself.

For other content types, like , the property will be a string.

Streaming

You can configure the type of the property using Axios' object. By default, is set to , which means Axios will try to parse the response as JSON.

However, that isn't correct if you're looking to, say, download an image using Axios. You can set to to get the response as an ArrayBuffer:

You can also set to to get the response as a Node.js stream:


Sours: https://masteringjs.io/tutorials/axios/response-body
091 Axios Error Handling

How to use

response

function

in

axios

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

instance.interceptors.response.use(response => { if (response.status === ) { return response; } return Promise.reject(response); }, error => { if (error) { let msg = ''; if (error.response && error.response.status === ) { msg = error.response.data.msg; return; } msg = '网络异常,请检查你的网络。'; Toast({ content: msg, timeout: , background: "#f" }); } else { Toast({ content: '未知错误。', timeout: , background: "#f" }); } return Promise.reject(error); });
axiosIntercept.interceptors.response.use(function (response) { if (err.response) { switch (err.response.status) { case
$http.interceptors.response.use(response => response, error => { const {router} = store.getState() if (error.response.status === && authPathRegExp.test(router.location.pathname)) { store.dispatch(Actions.setAuth({isAuth: false, access_token: null})) store.dispatch(push('/auth/login')) store.dispatch(Actions.addMessage(`[${router.location.pathname}] Login again`)) } return Promise.reject(error) })
api.interceptors.response.use( async response => { console.log('Response Interceptor = ', JSON.stringify(response.data)); return response; }, error => { return Promise.reject(error); }, );
instance.interceptors.response.use(function (response) { tryToUpdateAuthTokenFromHeaders(response.headers); return response; }, (error) => { tryToUpdateAuthTokenFromHeaders(error.response.headers); return Promise.reject(error); });
instance.interceptors.response.use( response => { return response; }, error => { if (error.response.data.statusCode === ) { logoutByUnauthorized(); } return Promise.reject(error); } );
service.interceptors.response.use(response => { if (response.status >= || response.status < ) { errorfn.apply(this, arguments); } return response; }, error => { errorfn.apply(this, arguments); return Promise.reject(error); });
axios.interceptors.response.use( response => { return response; }, error => { if (error.response && error.response.status === ) { logout()(store.dispatch); window.location.href = '/login'; } } );
axios.interceptors.response.use(function(config){ Toast.hide() return config })
instance.interceptors.response.use(function (response) { return response; }, function (error) { return Promise.reject(error); });
axios.interceptors.response.use( axiosConfig => axiosConfig, error => error.response || {}, );
instance.interceptors.response.use(response => { if (response.status === ) { return response; } return Promise.reject(response); }, error => { if (error) { let msg = ''; if (error.response && error.response.status === ) { msg = error.response.data.msg; return; } msg = '网络异常,请检查你的网络。'; Toast({ content: msg, timeout: , background: "#f" }); } else { Toast({ content: '未知错误。', timeout: , background: "#f" }); } return Promise.reject(error); });
axios.interceptors.response.use( response => response, error => error.response)
axios.interceptors.response.use((config)=>{ Toast.hide(); return config });
api.interceptors.response.use( (response) => { console.log("Response Interceptor = ", JSON.stringify(response.data)); return response; }, (error) => { return Promise.reject(error); } );
Sours: https://www.tabnine.com/code/javascript/functions/axios/response

Response status axios

axios / axios Public

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:

Sours: https://github.com/axios/axios
44. Axios Interceptors in React. Apply both Request and Response Interceptors in ReactJS.

How to make HTTP requests with Axios

Editor&#;s note: This Axios tutorial was last updated on 26 January

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: , // `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: , node_id: "MDEyOk9yZ2FuaXphdGlvbjYwMDkzNQ==", avatar_url: "https://avatars1.githubusercontent.com/u/?v=4", gravatar_id: "", …} // => // => OK // => {x-ratelimit-limit: "60", x-github-media-type: "github.v3", x-ratelimit-remaining: "60", last-modified: "Wed, 01 Aug GMT", etag: "W/"cce0bdbe8c9"", …} // => {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: TZ // => Date created: TZ

    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: TZ // => Date created: TZ

    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);

    ’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-baraxios/0a3acf92/dist/nprogress.css" /> <script src="https://cdn.rawgit.com/rikmms/progress-baraxios/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 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/

    Now discussing:

    .



    685 686 687 688 689