SoFunction
Updated on 2025-03-06

Axios get post request to pass parameters

Axios Overview

First of all, axios is a promise based on the http client for browser and

Features:

Supports browser and

Support promise

Ability to intercept requests and responses

Ability to convert request and response data

Cancel the request

Automatically convert json data

The browser side supports preventing CSRF (cross-site request forgery)

1. Installation

npm installation

$ npm install axios
bower installation

$ bower install axios
Introduction through cdn

<script src="/axios/dist/"></script>

First, you need to install axios
Next, introduce axios in

import axios from "axios";

Unlike many third-party modules, axios cannot use the use method. Since axios came out earlier than vue, it needs to be placed in the prototype object of vue.

.$axios = axios;

Then we can use axios in it

created:function(){
  this.$("/seller",{"id":123}).then(res=>{
    ();
  });
}

1. Make a get request

<input  type="button" value="get01"/>
<script>
    $("#get01Id").click(function () {
        ('http://localhost:8080/user/findById?id=1')
            .then(function (value) {
                (value);
            })
            .catch(function (reason) {
                (reason);
            })
    })
</script>

Another form:

<input  type="button" value="get02"/>
<script>
    $("#get02Id").click(function () {
        ('http://localhost:8080/user/findById', {
            params: {
                id: 1
            }
        })
            .then(function (value) {
                (value);
            })
            .catch(function (reason) {
                (reason);
            })
    })
</script>

2. Make a post request
In the official documentation, it looks like this:

   ('/user', {
            firstName: 'Fred',
            lastName: 'Flintstone'
        }).then(function (res) {
            (res);
        }).catch(function (err) {
            (err);
    });

However, if you write this, the backend will not receive data

So when we use post request, we need to write the passing parameters like this:

<input  type="button" value="post01"/>
<script>
    $("#post01Id").click(function () {
        var params = new URLSearchParams();
        ('username', 'sertyu');
        ('password', 'dfghjd');
        ('http://localhost:8080/user/addUser1', params)
            .then(function (value) {
                (value);
            })
            .catch(function (reason) {
                (reason);
            });
    })
</script>

3. Execute multiple concurrent requests

&lt;input  type="button" value="Point 01"/&gt;
&lt;script&gt;
    function getUser1() {
        return ('http://localhost:8080/user/findById?id=1');
    }
​
    function getUser2() {
        return ('http://localhost:8080/user/findById?id=2');
    }
​
    $("#buttonId").click(function () {
        ([getUser1(), getUser2()])
            .then((function (user1, user2) {
                alert();
                alert();
            }))
    })
&lt;/script&gt;

Another form:

&lt;input  type="button" value="Point 02"/&gt;
&lt;script&gt;
    $("#button02Id").click(function () {
        ([
            ('http://localhost:8080/user/findById?id=1'),
            ('http://localhost:8080/user/findById?id=2')
        ])
            .then((function (user1, user2) {
                alert();
                alert();
            }))
    })
&lt;/script&gt;

When all requests are completed, an array will be received containing the response objects, the order of the request is the same as the order of the request sent. You can use the split into multiple separate response objects

3. axiosAPI

(I) Requests can be created by passing relevant configurations to Axios
axios(config)

&lt;input  type="button" value="point"/&gt;
&lt;script&gt;
    $("#buttonId").click(function () {
        var params = new URLSearchParams();
        ('username','trewwe');
        ('password','wertyu');
        // Make a post request        axios({
            method:'post',
            url:'http://localhost:8080/user/addUser1',
            data:params
        });
    })
&lt;/script&gt;

axios(url[,config])

&lt;input  type="button" value="point"/&gt;
&lt;script&gt;
    $("#buttonId").click(function () {
        // Initiate a get request, (get is the default request method)        axios('http://localhost:8080/user/getWord');
    })
&lt;/script&gt;

(II) Request method alias

(config)
(url[, config])
(url[,config])
(url[, config])
(url[, config])
(url[, data[, config]])
(url[, data[, config]])
(url[, data[, config]])

When using alias methods, url, method, and data properties do not have to be specified in the configuration

(III) Concurrent requests are auxiliary functions that help handle concurrent requests

//iterable is an iterable parameter such as an array, etc.(iterable)
//Callback will be executed until all requests are completed(callback)

(IV) Create an instance and use custom configuration
([config])

var instance = ({
  baseURL:"http://localhost:8080/user/getWord",
  timeout:1000,
  headers: {'X-Custom-Header':'foobar'}
});

2. Example method

The following is the instance method. Note that the defined configuration will be merged with the configuration of the instance created with create.

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

4. Request configuration

The configuration option for requesting is only the url option. If the method option is not defined, then it defaults to issue the request in get mode.

{
    // url is the server URL used for request    url: '/user/getWord',
​
    // method is the method used when creating a request    method: 'get', // The default is get​
    // The baseURL will be automatically added before the url unless the url is an absolute path.    // It can facilitate the passing of relative paths to axios instance by setting a baseURL    baseURL: 'http://localhost:8080/',
​
    // transformRequest allows modifying request data before sending to the server    // Only use the request methods of 'PUT', 'POST' and 'PATCH'    // The function in the following array must return a string, or an ArrayBuffer, or a Stream    transformRequest: [function (data) {
        // Perform arbitrary conversion of data​
        return data;
    }],
​
    // transformResponse allows modification of response data before being passed to then/catch    transformResponse: [function (data) {
        // Perform arbitrary conversion of data​
        return data;
    }],
​
    // headers are the custom request header to be sent soon    headers: {'X-Requested-With': 'XMLHttpRequest'},
​
    // params are URL parameters to be sent with the request    // Must be a plain object or URLSearchParams object    params: {
        ID: 12345
    },
​
    // paramsSerializer is a function responsible for params serialization    // (. /package/qs, //)
    paramsSerializer: function (params) {
        return (params, {arrayFormat: 'brackets'})
    },
​
    // data is data sent as the requesting body    // Applicable only to these request methods 'PUT', 'POST', and 'PATCH'    // When transformRequest is not set, it must be one of the following types:    // - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams
    // - Browser exclusive: FormData, File, Blob    // - Node exclusive: Stream    data: {
        firstName: 'yuyao'
    },
​
    // timeout Specifies the number of milliseconds for the request timeout (0 means no timeout)    // If the request charge exceeds timeout, the request will be interrupted    timeout: 1000,
​
    // withCredentials indicates whether credentials are required when requesting across domains    withCredentials: false, // Default​
    // adapter allows custom processing of requests to make testing easier    // Return a promise and apply a valid response (see [response docs](#response-api)).    adapter: function (config) {
        /* ... */
    },
​
    // auth means that HTTP basic verification should be used and credentials should be provided    // This will set an Authorization header, overwriting any existing custom Authorization header set using headers    auth: {
        username: 'zhangsan',
        password: '12345'
    },
​
    // responseType represents the data type of the server response, which can be 'arraybuffer', 'blob', 'document', 'json', 'text', 'stream'    responseType: 'json', // Default​
    // xsrfCookieName 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 hosts the value of xsrf token    xsrfHeaderName: 'X-XSRF-TOKEN', // Default​
    // onUploadProgress allows processing of progress events for uploads    onUploadProgress: function (progressEvent) {
        // Handling of native progress events    },
​
    // onDownloadProgress allows processing of 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 the status code for the given HTTP response to be resolve or reject promise .    // If validateStatus returns true (or set to null or undefined ), the promise will be resolved; otherwise, the promise will be rejected    validateStatus: function (status) {
        return status &gt;= 200 &amp;&amp; status &lt; 300; // Default    },
​
    // maxRedirects defines the maximum number of redirects in follow    // If set to 0, no redirects will be followed    maxRedirects: 5, // Default​
    // httpAgent and httpsAgent are used in , respectively, to define the custom proxy used when executing http and https. Allows configuring options like this:    // keepAlive is not enabled by default    httpAgent: new ({keepAlive: true}),
    httpsAgent: new ({keepAlive: true}),
​
    // 'proxy' defines the host name and port of the proxy server    // auth means that HTTP basic verification 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 the header.    proxy: {
        host: '127.0.0.1',
        port: 9000,
        auth: {
            username: 'lisi',
            password: '54321'
        }
    },
​
    // cancelToken Specifies the cancel token used to cancel the request    cancelToken: new CancelToken(function (cancel) {
    })
}

5. Response content

{
  data:{},
  status:200,
  //The http status text returned from the server  statusText:'OK',
  //Response header information  headers: {},
  //config is some configuration information when requesting  config: {}
}

This is how to get the response information

<input  type="button" value="get"/>
<script>
    $("#getId").click(function () {
        ('http://localhost:8080/user/findById?id=1')
            .then(function (value) {
                ("data:"+);
                ("status:"+);
                ("statusText:"+);
                ("headers:"+);
                ("config:"+);
            })
            .catch(function (reason) {
                (reason);
            })
    })
</script>

6. Default configuration

The default configuration is valid for all requests

1. Global default configuration

 = 'http://localhost:8080/';
['Authorization'] = AUTH_TOKEN;
['content-Type'] = 'appliction/x-www-form-urlencoded';

2. Customized instance default settings

//Configure the default configuration when creating an instancevar instance = ({
    baseURL: 'http://localhost:8080/'
});
//Modify the configuration when the instance is created["Authorization"] = AUTH_TOKEN;

3. There are priority levels in the configuration
The config configuration will be merged with priority level, in the order of the default configuration in lib/, then the default configuration in the instance, and finally the configuration of the config parameter in the request. The higher the level, the higher the following level will be, and the following will override the previous example.

//When creating an instance, the default configuration in the library directory will be used//The value configured here is 0, from the default value of libraryvar instance = ();
//Return to overwrite the default value of the library//Now all requests will be sent after 2.5S = 2500;
//The timeout here returns to cover the previous 2.5S and becomes 5s('/longRequest',{
  timeout: 5000
});

7. Interceptor

1. You can intercept the request and response before reaching then/catch

//Add a request interceptor(function(config){
  // Do some operations before the request is issued  return config;
},function(err){
  //Do something with request error
  return (error);
});
//Add a response interceptor(function(res){
  //The returned data is processed here  return res;
},function(err){
  //Do something with response error
  return (error);
})

2. Cancel the interceptor

var myInterceptor = (function(){/*....*/});
(myInterceptor);

3. Add an interceptor to a custom axios instance

var instance = ();
(function(){})

8. Error handling

&lt;input  type="button" value="get"/&gt;
&lt;script&gt;
    $("#getId").click(function () {
        ('http://localhost:8080/user/findById?id=100')
            .catch(function (error) {
                if () {
                    //The request has been issued, but the status returned by the server response is not within the range of 2xx                    ("data:"+);
                    ("status:"+);
                    ("header:"+);
                } else {
                    //Some errors are triggered when setting the request                    ('Error', );
                }
                ();
            });
    })
&lt;/script&gt;

9. Cancel

Cancel a request through a cancel token

Create a cancel token through factory functions

&lt;input  type="button" value="get"/&gt;
&lt;input  type="button" value="unGet"/&gt;
&lt;script&gt;
    var CancelToken = ;
    var source = ();
    $("#getId").click(function () {
        ('http://localhost:8080/user/findById?id=1', {
            cancelToken: 
        })
            .then(function (value) {
                (value);
            })
            .catch(function (thrown) {
            if ((thrown)) {
                ('Request canceled', );
            } else {
                //handle error
            }
        });
    });
    $("#unGetId").click(function () {
        //Cancel the request (the parameters of the information can be set)        ("The operation was cancelled by the user");
    });
&lt;/script&gt;

This is the article about axios get post request passing parameters. For more related axios get post request passing parameters, please search for my previous article or continue browsing the related articles below. I hope everyone will support me in the future!