Axios parameters

  1. Request Configuration

    These configuration objects can be used not only in axios( ), but also in .request( ), .post( ) and other request methods.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    {
    // server url address
    url: '/user',

    // request method
    method: 'get', // default is get

    // Set the basic structure of url, such as http, localhost, 3000, etc. After setting the baseURL, you only need to write the follow-up path.
    baseURL: 'https://some-domain.com/api/',

    // Process the request data and send it to the server after processing. That is, preprocessing request parameters.
    transformRequest: [function (data, headers) {
    // Do whatever you want to transform the data
    return data;
    }],

    // That is to preprocess the response result.
    transformResponse: [function (data) {
    // Do whatever you want to transform the data
    return data;
    }],

    // Configure request header information. When performing identity verification on some projects, a special identifier is required to be added to the request header information to determine whether the request meets the conditions.
    headers: {'X-Requested-With': 'XMLHttpRequest'},

    // Set the url parameter. What is configured is an object, and various parameters are written. More readable than writing in url.
    params: {
    ID: 12345
    },

    // Parameter serialization configuration item, not commonly used. Serialize request parameters and convert them to strings. (The server side requires this configuration when the data format is different)
    paramsSerializer: function (params) {
    return Qs. stringify(params, {arrayFormat: 'brackets'})
    },

    // Request body settings (object form). Axios will convert it into a json format string and pass it on. Select the format according to the project requirements.
    data: {
    firstName: 'Fred'
    },

    // Request body settings (string format). axios will pass it straight through. Select the format according to the project requirements.
    data: 'Country=Brasil&City=Belo Horizonte',

    // overtime time. If this time elapses after sending the request, the request will be cancelled.
    timeout: 1000, // default is `0` (no timeout)

    // Settings for carrying cookies when cross-domain requests are made.
    withCredentials: false, // default

    // Request adapter settings. One is Ajax in the browser, and the other is sending http in Node.js.
    adapter: function (config) {
    /* ... */
    },

    // Basic validation of the request, not commonly used
    auth: {
    username: 'janedoe',
    password: 's00pers3cret'
    },

    // Response result format setting
    responseType: 'json', // default

    // Response result encoding, charset setting.
    responseEncoding: 'utf8', // default

    // Cross-origin request identifier. Set the name of the cookie.
    xsrfCookieName: 'XSRF-TOKEN', // default

    // Cross-origin request identifier. Set the request header information.
    xsrfHeaderName: 'X-XSRF-TOKEN', // default
    /* The above two are a security setting. It is a protective effect to ensure that the request comes from your own client instead of an unknown page. because the server is returning the result
    A unique identifier will be returned, and the identifier must be sent the next time the request is sent, and the server will respond after verification. But some web pages will add some links
    Then, send a request to the server. If these two unique identifiers are not added, the request for the web page link may affect the results returned by the server. joined these two
    After the logo, only the client sends the logo, and other web pages have no logo, so cross-site attacks can be avoided. */


    // callback when uploading
    onUploadProgress: function (progressEvent) {
    },

    // Callback when downloading
    onDownloadProgress: function (progressEvent) {
    },

    // http response body maximum size
    maxContentLength: 2000,

    // The maximum content of the request body
    maxBodyLength: 2000,

    // Set the success condition of the response result. No need to change, unless you set the success/failure rules yourself.
    validateStatus: function (status) {
    return status >= 200 && status < 300; // default
    },

    // Maximum number of jumps. The server request sent may have a jump. Generally, it is only used in Node.js, and Ajax is not used.
    maxRedirects: 5, // default

    // Set the socket file location, the function is to send a request to the docker.sock process, that is, data forwarding. There is a priority relationship with the proxy. if set
    // socket, proxy is also set, socket is used first.
    socketPath: null, // default

    // Client information setting, setting whether to keep the connection, not commonly used.
    httpAgent: new http.Agent({ keepAlive: true }),
    httpsAgent: new https.Agent({ keepAlive: true }),

    // Set the proxy. It is often used in node.js, such as switching the client address in a crawler request.
    proxy: {
    protocol: 'https',
    host: '127.0.0.1',
    port: 9000,
    auth: {
    username: 'mikeymike',
    password: 'rapunz3l'
    }
    },

    // ajax request unset
    cancelToken: new CancelToken(function (cancel) {
    }),

    // an alternative way to cancel Axios requests using AbortController
    signal: new AbortController(). signal,

    // Decompress the response result, only for node.js.
    decompress: true // default

    // `insecureHTTPParser` boolean.
    // Indicates where to use an insecure HTTP parser that accepts invalid HTTP headers.
    // This may allow interoperability with non-conformant HTTP implementations.
    // Using the insecure parser should be avoided.
    // see options https://nodejs.org/dist/latest-v12.x/docs/api/http.html#http_http_request_url_options_callback
    // see also https://nodejs.org/en/blog/vulnerability/february-2020-security-releases/#strict-http-header-parsing-none
    insecureHTTPParser: undefined // default

    // transitional options for backward compatibility that may be removed in the newer versions
    transitional: {
    // silent JSON parsing mode
    // `true` - ignore JSON parsing errors and set response.data to null if parsing failed (old behavior)
    // `false` - throw SyntaxError if JSON parsing failed (Note: responseType must be set to 'json')
    silentJSONParsing: true, // default value for the current Axios version

    // try to parse the response string as JSON even if `responseType` is not 'json'
    forcedJSONParsing: true,

    // throw ETIMEDOUT error instead of generic ECONNABORTED on request timeouts
    clarifyTimeoutError: false,
    }
    }

  1. Axios default configuration

    Practical trick, you can set the repeated configuration in the default configuration to simplify the code. axios.default.[config]

    Axios parameters (that is, configuration objects) can be configured by default.

    When the default configuration is not done, the code is as follows, and the method and url must be set every time an axios request is sent.

    1
    2
    3
    4
    5
    6
    7
    8
    btns[0].onclick = function(){
    axios({
    method: 'GET',
    url: 'http://localhost:3000/posts'
    }).then(response => {
    console. log(response);
    });
    }

    After doing the default configuration,

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    axios.default.method = 'GET';
    axios.default.baseURL = 'http://localhost:3000';

    btns[0].onclick = function(){
    axios({
    url: 'posts'
    }).then(response => {
    console. log(response);
    });
    }

Share