Easy Tutorial
❮ Vuejs Ajax Vue Mixins ❯

Vue.js Ajax (axios)

Vue.js 2.0 recommends using axios to handle ajax requests.

Axios is a Promise-based HTTP client that can be used in browsers and node.js.

Github Open Source Address: https://github.com/axios/axios

Installation Methods

Using CDN:

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

or

<script src="https://cdn.staticfile.org/axios/0.18.0/axios.min.js"></script>

Using npm:

$ npm install axios

Using bower:

$ bower install axios

Using yarn:

$ yarn add axios

Browser Support


GET Method

We can easily fetch JSON data:

GET Example

new Vue({
  el: '#app',
  data () {
    return {
      info: null
    }
  },
  mounted () {
    axios
      .get('https://www.tutorialpro.org/try/ajax/json_demo.json')
      .then(response => (this.info = response))
      .catch(function (error) { // Request failure handling
        console.log(error);
      });
  }
})

Using response.data to read JSON data:

GET Example

<div id="app">
  <h1>Website List</h1>
  <div
    v-for="site in info"
  >
    {{ site.name }}
  </div>
</div>
<script type="text/javascript">
new Vue({
  el: '#app',
  data () {
    return {
      info: null
    }
  },
  mounted () {
    axios
      .get('https://www.tutorialpro.org/try/ajax/json_demo.json')
      .then(response => (this.info = response.data.sites))
      .catch(function (error) { // Request failure handling
        console.log(error);
      });
  }
})
</script>

The format for passing parameters in the GET method is as follows:

Parameter Passing Explanation

// Directly add parameters to the URL, e.g., ID=12345
axios.get('/user?ID=12345')
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

// Alternatively, set parameters using params:
axios.get('/user', {
    params: {
      ID: 12345
    }
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

POST Method

POST Example

new Vue({
  el: '#app',
  data () {
    return {
      info: null
    }
  },
  mounted () {
    axios
      .post('https://www.tutorialpro.org/try/ajax/demo_axios_post.php')
      .then(response => (this.info = response))
      .catch(function (error) { // Request failure handling
        console.log(error);
      });
  }
})

POST Method Parameter Formatting:

Parameter Explanation

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

Executing Multiple Concurrent Requests

Example

function getUserAccount() {
  return axios.get('/user/12345');
}

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

axios API

Requests can be made by passing the relevant config to axios.

Example

axios(config)
// Send a POST request
axios({
  method: 'post',
  url: '/user/12345',
  data: {
    firstName: 'Fred',
    lastName: 'Flintstone'
  }
});
// GET request for remote image
axios({
  method: 'get',
  url: 'https://static.tutorialpro.org/images/tutorialpro-logo.png',
  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.post(url[, data[, config]])
axios.put(url[, data[, config]])
axios.patch(url[, data[, config]])

Note: When using alias methods, the url, method, and data properties do not need to be specified in the config.

Concurrency

Helper functions for handling concurrent requests:

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

Creating an Instance

You can create a new instance with a custom config:

axios.create([config])
const instance = 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#post(url[, data[, config]])
axios#put(url[, data[, config]])
axios#patch(url[, data[, config]])

Request Config

These are the available config options for making requests. Only the url is required. If the method is not specified, the request will default to GET.

{
  // `url` is the server URL that will be used for the request
  url: "/user",

  // `method` is the request method to be used when making the request
  method: "get", // default

// baseURL will be prepended to url unless url is an absolute URL. // It can be convenient to set a 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", and "PATCH" // The functions in the array should return a string, or an instance of ArrayBuffer or Stream transformRequest: [function (data) { // Perform any transformations on the data

return data; }],

// transformResponse allows changes to the response data before it is passed to then/catch transformResponse: [function (data) { // Perform any transformations on the data

return data; }],

// headers are custom headers to be sent headers: {"X-Requested-With": "XMLHttpRequest"},

// params are the URL parameters to be sent with the request // Must be a plain object or a URLSearchParams object params: { ID: 12345 },

// paramsSerializer is an optional function in charge of serializing params // (e.g. https://www.npmjs.com/package/qs, https://api.jquery.com/jquery.param/) paramsSerializer: function(params) { return Qs.stringify(params, {arrayFormat: "brackets"}) },

// data is the data to be sent as the request body // Only applicable for request methods "PUT", "POST", and "PATCH" // When no transformRequest is set, must be of one of the following types: // - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams // - Browser specific: FormData, File, Blob // - Node specific: Stream data: { firstName: "Fred" },

// timeout specifies the number of milliseconds before the request times out (0 means no timeout) // If the request takes longer than timeout, the request will be aborted timeout: 1000,

// withCredentials indicates whether or not cross-site Access-Control requests should be made using credentials withCredentials: false, // default

// adapter allows custom handling of requests which makes testing easier // Returns a promise and applies a valid response (see response docs). 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 auth: { username: "janedoe", password: "s00pers3cret" },

// responseType indicates the type of data that the server will respond with // Options are "arraybuffer", "blob", "document", "json", "text", "stream" responseType: "json", // default

// xsrfCookieName is the name of the cookie to use as a value for xsrf token xsrfCookieName: "XSRF-TOKEN", // default

// xsrfHeaderName is the name of the HTTP header that carries the xsrf token value xsrfHeaderName: "X-XSRF-TOKEN", // default

// onUploadProgress allows handling of progress events for uploads

### Configuration Options

```javascript
onUploadProgress: function (progressEvent) {
  // Handle native progress events
},

// `onDownloadProgress` allows handling progress events for downloads
onDownloadProgress: function (progressEvent) {
  // Handle native progress events
},

// `maxContentLength` defines the maximum size of the response content allowed
maxContentLength: 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) {
  return status >= 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

// `httpAgent` and `httpsAgent` define custom agents to be used in node.js when executing http and https requests. Options can be configured like this:
// `keepAlive` is not enabled by default
httpAgent: new http.Agent({ keepAlive: true }),
httpsAgent: new https.Agent({ keepAlive: true }),

// "proxy" defines the hostname and port of the proxy server
// `auth` indicates that HTTP basic auth should be used to connect to the proxy, and provides credentials
// This will set a `Proxy-Authorization` header, overriding any existing `Proxy-Authorization` headers set via `headers`.
proxy: {
  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 the Cancellation section for more details)
cancelToken: new CancelToken(function (cancel) {
})
}

Response Structure

The response for an axios request contains the following information:

{
  // `data` is the response provided by the server
  data: {},

  // `status` is the HTTP status code
  status: 200,

  // `statusText` is the HTTP status message from the server response
  statusText: "OK",

  // `headers` are the headers sent by the server
  headers: {},

  // `config` is the configuration that was provided to the request
  config: {}
}

When using then, you will receive a response like this:

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 catch, or passing a rejection callback as the second parameter to then, the response can be accessed via the error object.

Default Values for Configuration

You can specify default values to be used for each request.

Global axios defaults:

axios.defaults.baseURL = 'https://api.example.com';
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 instance
var instance = axios.create({
  baseURL: 'https://api.example.com'
});

// Alter defaults after instance has been created
instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;

Configuration Priority Order

Configuration is merged with a specific precedence. This order is: library defaults found in lib/defaults.js, then the instance's defaults property, and finally the config argument for the request. The latter will take precedence over the former. Here's an example:

// Create instance using the library's default configuration
// The default timeout is `0` at this point
var instance = axios.create();

// Override the library's default timeout
// Now, all requests will wait 2.5 seconds before timing out
instance.defaults.timeout = 2500;

// Override timeout for a specific request that is known to take a long time
instance.get('/longRequest', {
  timeout: 5000
});

Interceptors

Intercept requests or responses before they are handled by then or catch.

// Add a request interceptor
axios.interceptors.request.use(function (config) {
    // Do something before request is sent
    return config;
  }, function (error) {
    // Do something with request error
    return Promise.reject(error);
  });

// Add a response interceptor
axios.interceptors.response.use(function (response) {
    // Do something with response data
    return response;
  }, function (error) {
    // Do something with response error
    return Promise.reject(error);
  });

If you need to remove an interceptor later, you can:

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

You can add interceptors to a custom axios instance.

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

Error Handling:

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 2xx
      console.log(error.response.data);
      console.log(error.response.status);
      console.log(error.response.headers);
    } else {
      // Something happened in setting up the request that triggered an Error
      console.log('Error', error.message);
    }
    console.log(error.config);
  });

You can define a custom HTTP status code error range using the validateStatus configuration option.

axios.get('/user/12345', {
  validateStatus: function (status) {
    return status < 500; // Reject only if the status code is greater than or equal to 500
  }
})

Cancellation

Cancel a request using a cancel token. The Axios cancel token API is based on the cancelable promises proposal.

You can create a cancel token using the CancelToken.source factory method, like this:

var CancelToken = axios.CancelToken;
var source = 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
  }
});

// Cancel the request (the message parameter is optional)
source.cancel('Operation canceled by the user.');

Alternatively, you can create a cancel token by passing an executor function to the CancelToken constructor:

var CancelToken = axios.CancelToken;
var cancel;

axios.get('/user/12345', {
  cancelToken: new CancelToken(function executor(c) {
    // The executor function receives a cancel function as a parameter
    cancel = c;
  })
});

// Cancel the request
cancel();

Note: You can use the same cancel token to cancel multiple requests.

Using application/x-www-form-urlencoded format for requests

By default, Axios serializes JavaScript objects to JSON. To use the application/x-www-form-urlencoded format, you can configure as follows.

Browser

In a browser environment, you can use the URLSearchParams API:

const params = new URLSearchParams();
params.append('param1', 'value1');
params.append('param2', 'value2');
axios.post('/foo', params);

Note that URLSearchParams is not supported in all browsers.

Alternatively, you can use the qs library to encode the data:

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

// Or in another way (ES6),

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

Node.js Environment

In Node.js, you can use the querystring module:

const querystring = require('querystring');
axios.post('https://www.tutorialpro.org/', querystring.stringify({ foo: 'bar' }));

Similarly to the browser, you can also use the qs library.

Promises

Axios relies on the native ES6 Promise implementation that is supported.

If your environment does not support ES6 Promises, you can use a polyfill.

TypeScript Support

Axios includes TypeScript definitions.

import axios from "axios";
axios.get("/user?ID=12345");
❮ Vuejs Ajax Vue Mixins ❯