What is axios?
Axios is a promise based HTTP library that can be used in browsers and node JS.
axios attribute
-
URL is the server URL used for the request
url: '/user'
-
Method is the method used when creating the request
method: 'get', the default is get
-
The baseURL is automatically prefixed to the URL unless it is an absolute URL. It can set a baseURL to pass the relative URL (domain name) for the method of axios instance. For example: http://127.0.0.1:8080
baseURL: 'https://some-domain.com/api/', -
Headers are the custom request headers to be sent
headers: {'X-Requested-With': 'XMLHttpRequest'},
-
params is the URL parameter to be sent with the request; It must be a plain object or URLSearchParams object, and the request parameters are spliced on the URL.
params: { ID: 12345 },
-
Data is the data sent as the request body; It is only applicable to these request methods' PUT ',' POST ', and' PATCH '; Data splicing in request body
Not set in `transformRequest` When, it must be one of the following types: // - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams // -Browser specific: FormData, File, Blob // -Node exclusive: Stream data: { firstName: 'Fred' },
-
paramsSerializer is a function responsible for params serialization
paramsSerializer: function(params) { return Qs.stringify(params, {arrayFormat: 'brackets'}) },
-
Timeout specifies the number of milliseconds that the request timed out (0 means no timeout)
// If the call cost exceeds the 'timeout', the request will be interrupted timeout: 1000,
-
transformRequest allows you to modify the request data before sending it to the server. It can only be used in 'PUT', 'POST' and 'PATCH'
The functions in the array after these request methods must return a string, or ArrayBuffer, or StreamtransformRequest: [function (data, headers) { // Arbitrary conversion of data return data; }],
-
transformResponse allows you to modify the response data before passing it to then/catch
transformResponse: [function (data) { // Arbitrary conversion of data return data; }],
-
responseType indicates the data type of the server response, which can be 'arraybuffer', 'blob', 'document',
'json', 'text', 'stream'responseType: 'json', // default
-
withCredentials indicates whether credentials are required for cross domain requests
withCredentials: false, // default
-
adapter allows custom processing of requests to make testing easier
// Return a promise and apply a valid response adapter: function (config) { /* ... */ },
-
auth indicates that HTTP basic authentication should be used and credentials should be provided
// This will set an 'Authorization' header, overwriting any existing custom 'Authorization' header set with 'headers' auth: { username: 'janedoe', password: 's00pers3cret' },
-
Other properties
// `responseEncoding` indicates encoding to use for decoding responses // Note: Ignored for `responseType` of 'stream' or client-side requests responseEncoding: 'utf8', // default // `Xsrfcookie name ` is the name of the cookie used as the value of 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 processing progress events for uploads onUploadProgress: function (progressEvent) { // Do whatever you want with the native progress event }, // `onDownloadProgress ` allows processing progress events for downloads onDownloadProgress: function (progressEvent) { // Handling of native progress events }, // `maxContentLength ` defines the maximum size of the allowed response content maxContentLength: 2000, // `validateStatus ` defines whether the status code for a given HTTP response is resolve or reject promise. If 'validateStatus' returns' true' (or set to 'null' or 'undefined'), promise will be resolved; Otherwise, promise will be rejecte d validateStatus: function (status) { return status >= 200 && status < 300; // default }, // `maxRedirects ` is defined in node The maximum number of redirects of follow in JS // If set to 0, no redirection will follow 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 'are on node JS is used to define the custom proxy used when executing http and https. Allow options to 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 host name and port of the proxy server // `auth ` indicates that HTTP basic authentication should be used for connection proxy and provide credentials // This will set a 'proxy authorization' header, overwriting the existing custom 'proxy authorization' header set by using 'header'. proxy: { host: '127.0.0.1', port: 9000, auth: { username: 'mikeymike', password: 'rapunz3l' } }, // `cancelToken ` specifies the cancel token used to cancel the request // (see the Cancellation section later for more information) cancelToken: new CancelToken(function (cancel) { })
Request response parameters
- data is the response provided by the server
data: {},
- Status HTTP status code from the server response
status: 200,
- statusText HTTP status information from the server response
statusText: 'OK',
- headers the header of the server response
headers: {},
- config is the configuration information provided for the request
config: {}, // 'request' // `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: {}
Get request
- The json data sent by the back end is displayed on the browser
Send get request without parameters using Axios
-
First, axios is introduced
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
- Writing JavaScript code
<script> axios.get('/teachers/findByPage') .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); }); </script>
- Browser view
get request with parameters
-
get request code with parameters
axios.get('/teachers/findByPage', { params: { pageNum:2, pageSize:3 } }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); })
- Page effect
- Page effect
Post request
Passing object data using post request
-
Controller method
@PostMapping("/insert") @ApiOperation("insert") public void insert(@RequestBody Teachers teachers) { System.out.println(teachers); teachersService.insert(teachers); }
-
javaScript code
axios.post('http://localhost:8080/teachers/insert', { gid:123, tname:"Han Xin" }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); });
-
Background receiving data
axios API configuration call
The request can be created by passing the relevant configuration to axios
- axios(config)
// Send POST request axios({ method: 'post', url: '/user/12345', data: { firstName: 'Fred', lastName: 'Flintstone' } });
// Get remote picture 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 GET request (default method) axios('/user/12345');