Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Vue3 Ajax(axios)

Vue3 Ajax(axios)

The Vue version recommends using axios to complete ajax requests.

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

GitHub open-source address: https://github.com/axios/axios

Installation Method

Using CDN:



or



Using npm:

$ npm install axios

Using bower:

$ bower install axios

Using yarn:

$ yarn add axios

Usage

Import the default-exported axios object from the Axios module:

import axios from 'axios';

1. Make a GET Request

Make a request for the user with the given ID:

Example

axios.

get

(

'/user?ID=12345'

)

  .

then

(

function

(

response

)

{

   

// success handling

    console.

log

(

response

)

;

 

}

)

  .

catch

(

function

(

error

)

{

   

// error handling

    console.

log

(

error

)

;

 

}

)

  .

finally

(

function

(

)

{

   

// always executed

 

}

)

;

The above request can also be implemented like this:

Example

axios.

get

(

'/user'

,

{

    params

:

{

      ID

:

12345

   

}

 

}

)

  .

then

(

function

(

response

)

{

    console.

log

(

response

)

;

 

}

)

  .

catch

(

function

(

error

)

{

    console.

log

(

error

)

;

 

}

)

  .

finally

(

function

(

)

{

   

// always executed

 

}

)

;

If you want to use async/await, add the async keyword to the outer function/method.

Example

async

function

getUser

(

)

{

 

try

{

   

const

response

=

await axios.

get

(

'/user?ID=12345'

)

;

    console.

log

(

response

)

;

 

}

catch

(

error

)

{

    console.

error

(

error

)

;

 

}

}

Note: async/await is part of ECMAScript 2017 and is not supported in Internet Explorer and older browsers, so use it with caution.

2. Make a POST Request

Example

axios.

post

(

'/user'

,

{

    firstName

:

'Fred'

,

    lastName

:

'Flintstone'

 

}

)

  .

then

(

function

(

response

)

{

    console.

log

(

response

)

;

 

}

)

  .

catch

(

function

(

error

)

{

    console.

log

(

error

)

;

 

}

)

;

Execute multiple requests concurrently:

Example

function

getUserAccount

(

)

{

 

return

axios.

get

(

'/user/12345'

)

;

}

function

getUserPermissions

(

)

{

 

return

axios.

get

(

'/user/12345/permissions'

)

;

}

Promise.

all

(

[

getUserAccount

(

)

,

getUserPermissions

(

)

]

)

  .

then

(

function

(

results

)

{

   

const

acct

=

results

[

0

]

;

   

const

perm

=

results

[

1

]

;

 

}

)

;

Browser Support


GET Method

We can simply read JSON data:

GET Example

const

app

=

{

data

(

)

{

return

{

info

:

'

Ajax Test!!

'

}

}

,

mounted

(

)

{

axios

.

get

(

'

https://www.runoob.com/try/ajax/json_demo.json

'

)

.

then

(

response

=>

(

this

.

info

=

response

)

)

.

catch

(

function

(

error

)

{

//

Request Failure Handling

console

.

log

(

error

)

;

}

)

;

}

}

Vue

.

createApp

(

app

)

.

mount

(

'

#app

'

)

Try it »

Use response.data to read JSON data:

GET Example

<div id="app">
<h1>

Site List

h1

<div v-for=">

site in info

"

{{ site.name }}

div

div

<script type="text/javascript">

const app = { data() { return { info: 'Ajax Test!!' } }, mounted () { axios .get('https://www.runoob.com/try/ajax/json_demo.json') .then(response => (this.info = response.data.sites)) .catch(function (error) { // request failure handling console.log(error); }); } } Vue.createApp(app).mount('#app')

script

Try it »

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

Parameter Passing Notes

//

Add the parameter ID=12345 directly to the URL

axios

.

get

(

'

/user?ID=12345

'

)

.

then

(

function

(

response

)

{

console

.

log

(

response

)

;

}

)

.

catch

(

function

(

error

)

{

console

.

log

(

error

)

;

}

)

;

//

You can also set parameters via params:

axios

.

get

(

'

/user

'

,

{

params

:

{

ID

:

12345

}

}

)

.

then

(

function

(

response

)

{

console

.

log

(

response

)

;

}

)

.

catch

(

function

(

error

)

{

console

.

log

(

error

)

;

}

)

;


POST Method

POST Example

const

app

=

{

data

(

)

{

return

{

info

:

null

}

}

,

mounted

(

)

{

axios

.

post

(

'

https://www.runoob.com/try/ajax/demo_axios_post.php

'

)

.

then

(

response

=>

(

this

.

info

=

response

)

)

.

catch

(

function

(

error

)

{

//

Request Failure Handling

console

.

log

(

error

)

;

}

)

;

}

}

Vue

.

createApp

(

app

)

.

mount

(

'

#app

'

)

Try it »

The format for passing parameters with the POST method is as follows:

Parameter Passing Notes

axios

.

post

(

'

/user

'

,

{

firstName

:

'

Fred

'

,

//

Parameter firstName

lastName

:

'

Flintstone

'

//

Parameter lastName

}

)

.

then

(

function

(

response

)

{

console

.

log

(

response

)

;

}

)

.

catch

(

function

(

error

)

{

console

.

log

(

error

)

;

}

)

;


Execute 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 have now completed

}

)

)

;


axios API

You can create a request by passing the relevant configuration to axios.

Example

axios

(

config

)

//

Send a POST request

axios

(

{

method

:

'

post

'

,

url

:

'

/user/12345

'

,

data

:

{

firstName

:

'

Fred

'

,

lastName

:

'

Flintstone

'

}

}

)

;

//

GET a remote image

axios

(

{

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 (the default method)

axios

(

'

/user/12345

'

)

;

Request Method Aliases

For convenience, the official library provides aliases for all supported request methods, which you can use directly to make requests:

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)

Create an Instance

You can create a new axios instance with custom configuration:

axios.create([config])

const instance = axios.create({

  baseURL: 'https://some-domain.com/api/',

  timeout: 1000,

  headers: {'X-Custom-Header': 'foobar'}

});

Instance Methods

The following instance methods are available. The specified config is merged with the instance's 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

Below are the configuration options available when creating a request. Note that only url is required. If method is not specified, the request defaults to the get method.

{

  // `url` is the server URL used for the request

  url: "/user",



  // `method` is the method used when creating the request

  method: "get", // 默认是 get



  // `baseURL` will be automatically prepended to `url`, unless `url` is an absolute URL.

  // It can pass relative URLs to the axios instance methods by setting a `baseURL`

  baseURL: "https://some-domain.com/api/",



  // `transformRequest` allows modifying request data before sending to the server

  // Only usable in "PUT", "POST", and "PATCH" request methods

  // The function in the following array must return a string, ArrayBuffer, or Stream

  transformRequest: [function (data) {

    // Perform arbitrary transformations on data



    return data;

  }],



  // `transformResponse` allows modifying the response data before passing it to then/catch

  transformResponse: [function (data) {

    // Perform arbitrary transformations on data



    return data;

  }],



  // `headers` are the custom request headers that will be sent

  headers: {"X-Requested-With": "XMLHttpRequest"},



  // `params` are the URL parameters that will be sent with the request

  // Must be a plain object or URLSearchParams object

  params: {

    ID: 12345

  },



  // `paramsSerializer` is a function responsible for serializing `params`

  // (e.g. https://www.npmjs.com/package/qs, http://api.jquery.com/jquery.param/)

  paramsSerializer: function(params) {

    return Qs.stringify(params, {arrayFormat: "brackets"})

  },



  // `data` is the data sent as the request body

  // Only applies to these request methods "PUT", "POST", and "PATCH"

  // Must be one of the following types when `transformRequest` is not set:

  // - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams

  // - Browser exclusive: FormData, File, Blob

  // - Node exclusive: Stream

  data: {

    firstName: "Fred"

  },



  // `timeout` specifies the request timeout in milliseconds (0 means no timeout)

  // If the request takes longer than `timeout`, the request will be interrupted

  timeout: 1000,



  // `withCredentials` indicates whether credentials should be used for cross-origin requests

  withCredentials: false, // 默认的



  // `adapter` allows custom request handling, making tests easier

  // Returns a promise and applies a valid response (see [response docs](#response-api)).

  adapter: function (config) {

    /* ... */

  },



  // `auth` indicates that HTTP basic authentication should be used, and credentials provided

  // This will set an `Authorization` header, overwriting any custom `Authorization` header set using `headers`

  auth: {

    username: "janedoe",

    password: "s00pers3cret"

  },



  // `responseType` indicates the data type of the server response, which can be "arraybuffer", "blob", "document", "json", "text", or "stream"

  responseType: "json", // 默认的



  // `xsrfCookieName` is the name of the cookie used for the xsrf token value

  xsrfCookieName: "XSRF-TOKEN", // default



  // `xsrfHeaderName` is the name of the HTTP header that carries the xsrf token value

  xsrfHeaderName: "X-XSRF-TOKEN", // 默认的



  // `onUploadProgress` allows handling upload progress events

  onUploadProgress: function (progressEvent) {

    // Handling native progress events

  },



  // `onDownloadProgress` allows handling download progress events

  onDownloadProgress: function (progressEvent) {

    // Handling native progress events

  },



  // `maxContentLength` defines the maximum allowed response content size

  maxContentLength: 2000,



  // `validateStatus` defines whether to resolve or reject a 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; // 默认的

  },



  // `maxRedirects` 定义在 node.js 中 follow 的最大重定向数目

  // 如果设置为0,将不会 follow 任何重定向

  maxRedirects: 5, // 默认的



  // `httpAgent` 和 `httpsAgent` 分别在 node.js 中用于定义在执行 http 和 https 时使用的自定义代理。允许像这样配置选项:

  // `keepAlive` 默认没有启用

  httpAgent: new http.Agent({ keepAlive: true }),

  httpsAgent: new https.Agent({ keepAlive: true }),



  // "proxy" 定义代理服务器的主机名称和端口

  // `auth` 表示 HTTP 基础验证应当用于连接代理,并提供凭据

  // 这将会设置一个 `Proxy-Authorization` 头,覆写掉已有的通过使用 `header` 设置的自定义 `Proxy-Authorization` 头。

  proxy: {

    host: "127.0.0.1",

    port: 9000,

    auth: : {

      username: "mikeymike",

      password: "rapunz3l"

    }

  },



  // `cancelToken` 指定用于取消请求的 cancel token

  // (查看后面的 Cancellation 这节了解更多)

  cancelToken: new CancelToken(function (cancel) {

  })

}

Response Schema

The response of an axios request contains the following information:

{

  // `data` provided by the server response

  data: {},



  // `status` HTTP status code

  status: 200,



  // `statusText` is the HTTP status message from the server response

  statusText: "OK",



  // `headers` server response headers

  headers: {},



  // `config` is the configuration information provided for the request

  config: {}

}

When using then, you receive a response like the following:

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 rejection callback as then 's second parameter, the response can be accessed via error object.

Config Defaults

You can specify configuration defaults that will 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:

// 创建实例时设置配置的默认值

var instance = axios.create({

  baseURL: 'https://api.example.com'

});



// Modify default values after instance is created

instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;

Order of Config Precedence

Config is merged in a precedence order: the library defaults found in lib/defaults.js, then the instance's defaults property, and finally the request's config parameter. The latter takes precedence over the former. Here is an example:

// 使用由库提供的配置的默认值来创建实例

// The default value for the timeout configuration is `0`

var instance = axios.create();



// Override the library's timeout default value

// Now, all requests will wait 2.5 seconds before timeout

instance.defaults.timeout = 2500;



// Override timeout setting for requests known to take a long time

instance.get('/longRequest', {

  timeout: 5000

});

Interceptors

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

// 添加请求拦截器

axios.interceptors.request.use(function (config) {

    // What to do before sending the request

    return config;

  }, function (error) {

    // What to do about request errors

    return Promise.reject(error);

  });



// Add response interceptor

axios.interceptors.response.use(function (response) {

    // Do something with the response data

    return response;

  }, function (error) {

    // Do something about the response error

    return Promise.reject(error);

  });

If you want to remove an interceptor later, you can do it like this:

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

      // Request sent, but the server response status code is not in the 2xx range

      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 use the validateStatus config option to define a custom error range for HTTP status codes.

axios.get('/user/12345', {

  validateStatus: function (status) {

    return status < 500; // 状态码在大于或等于500时才会 reject

  }

})

Cancellation

Use a cancel token to cancel a request.

Axios's cancel token API is based oncancelable promises proposal

You can use the CancelToken.source factory method to create a cancel token, 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 request (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 CancelToken constructor:

var CancelToken = axios.CancelToken;

var cancel;



axios.get('/user/12345', {

  cancelToken: new CancelToken(function executor(c) {

    // executor function receives a cancel function as a parameter

    cancel = c;

  })

});



// Cancel request

cancel();

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

Use application/x-www-form-urlencoded when making requests

axios serializes JavaScript objects to JSON by default. If you want to use the application/x-www-form-urlencoded format, you can use the following configuration.

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

URLSearchParams is not supported by all browsers.

Additionally, you can use the qs library to encode 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('http://something.com/', querystring.stringify({ foo: 'bar' }));

Of course, just like in the browser, you can also use the qs library.

Promises

axios relies on the native ES6 Promise implementation andis supported.

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

TypeScript Support

axios includes TypeScript definitions.

import axios from "axios";

axios.get("/user?ID=12345");