### Axios GET Request Examples
Source: https://www.axios-http.cn/docs/example
This section demonstrates various ways to make GET requests using Axios. It covers basic URL parameters, passing parameters via the `params` object, and using async/await syntax for cleaner asynchronous code. Error handling with `.catch()` and `.finally()` is also shown. Note that async/await requires a compatible JavaScript environment (ECMAScript 2017+).
```javascript
const axios = require('axios');
// Make a request for a user with a given IDaxios.get('/user?ID=12345')
.then(function (response) {
// Handle success
console.log(response);
})
.catch(function (error) {
// Handle error
console.log(error);
})
.finally(function () {
// always executed
});
// Can be also done with a request
axios.get('/user', {
params: {
ID: 12345
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
})
.finally(function () {
// always executed
});
// Support async/await usage
async function getUser() {
try {
const response = await axios.get('/user?ID=12345');
console.log(response);
} catch (error) {
console.error(error);
}
}
```
--------------------------------
### Install Axios via Package Managers
Source: https://www.axios-http.cn/docs/intro
Commands to install the Axios library using popular JavaScript package managers. These commands add the dependency to your project's configuration file.
```bash
npm install axios
```
```bash
bower install axios
```
```bash
yarn add axios
```
```bash
pnpm add axios
```
--------------------------------
### Axios GET Request Example (JavaScript)
Source: https://www.axios-http.cn/docs/notes
Demonstrates a basic HTTP GET request using the Axios library. This snippet requires the Axios library to be installed and imported. It sends a GET request to the '/user' endpoint with a query parameter.
```javascript
import axios from 'axios';
axios.get('/user?ID=12345');
```
--------------------------------
### Make GET Requests with Axios URL Shortcut
Source: https://www.axios-http.cn/docs/api_intro
Demonstrates the shorthand syntax for performing a GET request by passing only the URL string to the axios function.
```javascript
// 发起一个 GET 请求 (默认请求方式)
axios('/user/12345');
```
--------------------------------
### Include Axios via CDN
Source: https://www.axios-http.cn/docs/intro
Methods to include the Axios library directly in HTML files using public CDN providers. This is suitable for browser-based projects without a build step.
```html
```
```html
```
--------------------------------
### Import Axios via CommonJS
Source: https://www.axios-http.cn/docs/intro
Directly importing pre-built CommonJS modules for specific environments when automatic resolution fails. This is useful for legacy Node.js or browser environments.
```javascript
const axios = require('axios/dist/browser/axios.cjs'); // browser
const axios = require('axios/dist/node/axios.cjs'); // node
```
--------------------------------
### Axios General Request Configuration
Source: https://www.axios-http.cn/docs/api_intro
Demonstrates how to make POST and GET requests using the general axios(config) method with detailed configuration options.
```APIDOC
## POST /user/12345
### Description
Initiates a POST request to the specified URL with provided data.
### Method
POST
### Endpoint
/user/12345
### Parameters
#### Request Body
- **firstName** (string) - Required - The first name of the user.
- **lastName** (string) - Required - The last name of the user.
### Request Example
```json
{
"firstName": "Fred",
"lastName": "Flintstone"
}
```
### Response
#### Success Response (200)
Details of the response depend on the server's implementation.
## GET http://bit.ly/2mTM3nY
### Description
Fetches data from a remote URL as a stream, suitable for large responses like images in Node.js.
### Method
GET
### Endpoint
http://bit.ly/2mTM3nY
### Parameters
#### Query Parameters
- **responseType** (string) - Optional - Set to 'stream' to receive the response as a stream.
### Request Example
```javascript
axios({
method: 'get',
url: 'http://bit.ly/2mTM3nY',
responseType: 'stream'
})
.then(function (response) {
response.data.pipe(fs.createWriteStream('ada_lovelace.jpg'))
});
```
### Response
#### Success Response (200)
The response data will be a stream that can be piped to a file or processed further.
```
--------------------------------
### Axios URL-based Request
Source: https://www.axios-http.cn/docs/api_intro
Shows how to make a GET request by simply providing the URL, with Axios defaulting to the GET method.
```APIDOC
## GET /user/12345
### Description
Initiates a GET request to the specified URL. This is the default method when only a URL is provided.
### Method
GET
### Endpoint
/user/12345
### Parameters
No specific parameters are required for this basic usage.
### Request Example
```javascript
axios('/user/12345');
```
### Response
#### Success Response (200)
Details of the response depend on the server's implementation.
```
--------------------------------
### Submit Multipart and URL-Encoded Forms
Source: https://www.axios-http.cn/docs/post_example
Provides examples for submitting data using multipart/form-data for file uploads and application/x-www-form-urlencoded for standard form submissions.
```javascript
// Multipart form-data
const {data} = await axios.post('https://httpbin.org/post', {
firstName: 'Fred',
lastName: 'Flintstone',
orders: [1, 2, 3],
photo: document.querySelector('#fileInput').files
}, {
headers: {
'Content-Type': 'multipart/form-data'
}
}
);
// URL encoded form
const {data} = await axios.post('https://httpbin.org/post', {
firstName: 'Fred',
lastName: 'Flintstone',
orders: [1, 2, 3]
}, {
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
})
```
--------------------------------
### 使用 Axios 实例进行请求
Source: https://www.axios-http.cn/docs/instance
Axios 实例提供了与全局 Axios 对象相同的请求方法(如 `get`, `post` 等),并且可以直接使用配置对象调用,这类似于全局的 `axios(config)`。这种方式特别适用于需要根据原始配置重新发送请求的场景,例如在响应拦截器中处理认证失败。
```javascript
const instance = axios.create({ baseURL: '/api' });
// 类似于 axios(config)
instance({
url: '/users',
method: 'get'
});
```
```javascript
instance.interceptors.response.use(undefined, async (error) => {
if (error.response?.status === 401) {
await refreshToken();
return instance(error.config); // 重新发送原始请求
}
throw error;
});
```
--------------------------------
### Axios Configuration Priority and Overriding Defaults
Source: https://www.axios-http.cn/docs/config_defaults
Understand the priority order for Axios configurations: library defaults, instance defaults, and request config parameters. Later configurations override earlier ones. This example demonstrates how to set a default timeout for an instance and then override it for a specific request.
```javascript
// 使用库提供的默认配置创建实例
// 此时超时配置的默认值是 `0`
const instance = axios.create();
// 重写库的超时默认值
// 现在,所有使用此实例的请求都将等待2.5秒,然后才会超时
instance.defaults.timeout = 2500;
// 重写此请求的超时时间,因为该请求需要很长时间
instance.get('/longRequest', {
timeout: 5000
});
```
--------------------------------
### Registering Language Configuration in Inert.js
Source: https://www.axios-http.cn/docs/translating
This snippet shows how to import a language-specific configuration file and add it to the 'langs' array in the inert.config.js file. Ensure the import statement precedes the 'langs' constant declaration. Replace '{language-shortcut}' with the appropriate ISO 639-1 code.
```javascript
const {language-shortcut}Config = require('./{language-shortcut}.config.js');
const langs = [
...
{
name: 'Some name that uniquely identifies your language, for example "English" or "German"',
prefix: "The same prefix as in the configuration file",
config: {language-shortcut}Config
}
...
];
```
--------------------------------
### Accessing Axios Response Data with .then()
Source: https://www.axios-http.cn/docs/res_schema
Demonstrates how to access various properties of the Axios response object within the success callback of a Promise, typically chained using `.then()`. This example shows logging the data, status, statusText, headers, and config from a GET request.
```javascript
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);
});
```
--------------------------------
### Axios Request Configuration Options
Source: https://www.axios-http.cn/docs/req_config
This section outlines the available configuration options for creating Axios HTTP requests. The `url` is mandatory, and `method` defaults to 'GET' if not specified.
```APIDOC
## Axios Request Configuration Options
### Description
This section details the various configuration options available when making HTTP requests with Axios. The `url` is mandatory, and `method` defaults to 'GET' if not specified.
### Method
GET, POST, PUT, DELETE, etc. (Defaults to 'GET' if not provided)
### Endpoint
`/websites/axios-http_cn` (This is a placeholder, actual endpoints will vary)
### Parameters
#### Path Parameters
None specified in the provided text.
#### Query Parameters
- **ID** (number) - Optional - Used in conjunction with `params` to send query parameters.
#### Request Body
- **data** (string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams, FormData, File, Blob, Stream, Buffer) - Optional - The data to be sent as the request body. Applicable for 'PUT', 'POST', 'DELETE', and 'PATCH' methods.
- **firstName** (string) - Optional - Example field for request body data.
- **Country** (string) - Optional - Example field for request body data.
- **City** (string) - Optional - Example field for request body data.
### Request Example
```json
{
"url": "/user",
"method": "get",
"baseURL": "https://some-domain.com/api/",
"headers": {"X-Requested-With": "XMLHttpRequest"},
"params": {"ID": 12345},
"data": {"firstName": "Fred"}
}
```
### Response
#### Success Response (200)
- **data** (any) - The response data, potentially transformed by `transformResponse`.
#### Response Example
```json
{
"example": "response body"
}
```
### Configuration Options Details:
- **`url`** (string): The server URL for the request. (Required)
- **`method`** (string): The HTTP method to use. Defaults to 'get'.
- **`baseURL`** (string): Automatically prepended to `url` unless `url` is absolute.
- **`transformRequest`** (Array): Allows modifying request data before sending. Applicable for 'PUT', 'POST', 'PATCH'.
- **`transformResponse`** (Array): Allows modifying response data before it's passed to `then/catch`.
- **`headers`** (Object): Custom request headers.
- **`params`** (Object | URLSearchParams): URL parameters to send with the request.
- **`paramsSerializer`** (Object): Options to customize the serialization of `params`.
- **`encode`** (Function): Custom encoder function for parameters.
- **`serialize`** (Function): Custom serializer function for entire params.
- **`indexes`** (boolean | null): Configuration for formatting array index in parameters.
- **`timeout`** (number): Request timeout in milliseconds. Defaults to 0 (never times out).
- **`withCredentials`** (boolean): Whether to send credentials for cross-origin requests. Defaults to false.
- **`adapter`** (Function): Allows custom request handling, useful for testing.
- **`auth`** (Object): For HTTP Basic Auth.
- **`username`** (string)
- **`password`** (string)
- **`responseType`** (string): The type of data expected in the response ('arraybuffer', 'document', 'json', 'text', 'stream', 'blob'). Defaults to 'json'.
- **`responseEncoding`** (string): Encoding for decoding the response (Node.js specific). Ignored for 'stream' or client-side requests. Defaults to 'utf8'.
- **`xsrfCookieName`** (string): Name of the cookie used for XSRF token. Defaults to 'XSRF-TOKEN'.
- **`xsrfHeaderName`** (string): Name of the header containing the XSRF token. Defaults to 'X-XSRF-TOKEN'.
- **`onUploadProgress`** (Function): Callback for upload progress events (browser-specific).
- **`onDownloadProgress`** (Function): Callback for download progress events (browser-specific).
- **`maxContentLength`** (number): Maximum byte length of the HTTP response content (Node.js specific).
- **`maxBodyLength`** (number): Maximum byte length of the HTTP request body (Node.js specific).
- **`validateStatus`** (Function): Defines whether a given HTTP status code should resolve or reject the promise. Defaults to resolving for status codes 200-299.
- **`maxRedirects`** (number): Maximum number of redirects to follow (Node.js specific). Defaults to 5.
- **`socketPath`** (string | null): Path to a UNIX socket for Node.js requests. Cannot be used with `proxy`.
- **`httpAgent`** (Object): Custom agent for HTTP requests (Node.js specific).
- **`httpsAgent`** (Object): Custom agent for HTTPS requests (Node.js specific).
- **`proxy`** (Object | boolean): Proxy server configuration for Node.js requests. Set to `false` to disable proxying.
- **`protocol`** (string): Protocol of the proxy server ('http' or 'https').
- **`host`** (string): Hostname of the proxy server.
- **`port`** (number): Port of the proxy server.
- **`auth`** (Object): Credentials for HTTP Basic auth to connect to the proxy.
- **`username`** (string)
- **`password`** (string)
- **`cancelToken`** (Object): Used for request cancellation.
- **`decompress`** (boolean): Indicates whether the response body should be decompressed.
```
--------------------------------
### Create Axios Instance with Custom Defaults
Source: https://www.axios-http.cn/docs/config_defaults
Create a custom Axios instance with its own default configuration, such as a specific baseURL. You can also modify the defaults of an existing instance after creation, for example, to set common authorization headers. This allows for more granular control over request configurations.
```javascript
// 创建实例时配置默认值
const instance = axios.create({
baseURL: 'https://api.example.com'
});
// 创建实例后修改默认值
instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;
```
--------------------------------
### Axios CommonJS TypeScript Integration
Source: https://www.axios-http.cn/docs/example
This snippet shows how to import Axios in a CommonJS environment to enable TypeScript type inference for better autocompletion and parameter type checking. It requires importing the default export of the axios module.
```javascript
const axios = require('axios').default;
// axios. can provide autocompletion and parameter type inference
```
--------------------------------
### Create Axios Instance
Source: https://www.axios-http.cn/docs/instance
Demonstrates how to create a new Axios instance with custom configurations such as baseURL, timeout, and headers.
```APIDOC
## Create Axios Instance
### Description
Creates a new Axios instance with custom configurations.
### Method
`axios.create([config])`
### Parameters
#### Request Body
- **config** (object) - Optional - Configuration object for the instance.
- **baseURL** (string) - The base URL to resolve requests made with this instance.
- **timeout** (number) - Allows setting a request timeout in milliseconds.
- **headers** (object) - An object containing custom headers to be sent with requests.
### Request Example
```javascript
const instance = axios.create({
baseURL: 'https://some-domain.com/api/',
timeout: 1000,
headers: {'X-Custom-Header': 'foobar'}
});
```
```
--------------------------------
### Make HTTP Requests with Axios Configuration
Source: https://www.axios-http.cn/docs/api_intro
Demonstrates how to initiate HTTP requests by passing a configuration object to the axios function. It covers both standard JSON data transmission and streaming binary data in Node.js environments.
```javascript
// 发起一个post请求
axios({
method: 'post',
url: '/user/12345',
data: {
firstName: 'Fred',
lastName: 'Flintstone'
}
});
```
```javascript
// 在 node.js 用GET请求获取远程图片
axios({
method: 'get',
url: 'http://bit.ly/2mTM3nY',
responseType: 'stream'
})
.then(function (response) {
response.data.pipe(fs.createWriteStream('ada_lovelace.jpg'))
});
```
--------------------------------
### Directly Call Instance with Config Object
Source: https://www.axios-http.cn/docs/instance
Shows how to call an Axios instance directly with a configuration object, similar to `axios(config)`.
```APIDOC
## Directly Call Instance with Config Object
### Description
Besides convenience methods like `instance.get()` or `instance.post()`, you can also call an Axios instance directly with a config object. This is the same as `axios(config)` and is useful for scenarios where you need to resend a request based on the original configuration.
### Request Example
```javascript
const instance = axios.create({ baseURL: '/api' });
// Similar to axios(config)
instance({
url: '/users',
method: 'get'
});
```
### Usage with Interceptors for Retries
This approach is convenient for implementing retry logic, for example, when handling authentication failures:
```javascript
instance.interceptors.response.use(undefined, async (error) => {
if (error.response?.status === 401) {
await refreshToken();
return instance(error.config); // Resend the original request
}
throw error;
});
```
```
--------------------------------
### Axios Instance Methods
Source: https://www.axios-http.cn/docs/instance
Lists the available methods on an Axios instance, which can be used with merged configurations.
```APIDOC
## Axios Instance Methods
### Description
Available methods on an Axios instance. Specified configurations will be merged with the instance's configuration.
### Methods
- `axios#request(config)`
- `axios#get(url[, config])`
- `axios#delete(url[, config])`
- `axios#head(url[, config])`
- `axios#options(url[, config])`
- `axios#post(url[, data[, config]])`
- `axios#put(url[, data[, config]])`
- `axios#patch(url[, data[, config]])`
- `axios#getUri([config])`
```
--------------------------------
### Perform a POST Request with Axios
Source: https://www.axios-http.cn/docs/post_example
Demonstrates how to send a POST request with a data object. It uses the .then() and .catch() methods to handle the successful response or potential errors.
```javascript
axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
```
--------------------------------
### Execute Concurrent Requests with Axios
Source: https://www.axios-http.cn/docs/post_example
Shows how to execute multiple asynchronous requests simultaneously using Promise.all. This is useful for fetching data from multiple endpoints in parallel.
```javascript
function getUserAccount() {
return axios.get('/user/12345');
}
function getUserPermissions() {
return axios.get('/user/12345/permissions');
}
const [acct, perm] = await Promise.all([getUserAccount(), getUserPermissions()]);
// OR
Promise.all([getUserAccount(), getUserPermissions()])
.then(function ([acct, perm]) {
// ...
});
```
--------------------------------
### Add Interceptors to Custom Instances
Source: https://www.axios-http.cn/docs/interceptors
Illustrates how to apply interceptors specifically to a custom Axios instance created via axios.create().
```javascript
const instance = axios.create();
instance.interceptors.request.use(function () {/*...*/});
```
--------------------------------
### 创建 Axios 实例
Source: https://www.axios-http.cn/docs/instance
使用 `axios.create()` 方法可以创建一个具有自定义配置(如 baseURL、timeout、headers)的 Axios 实例。这个实例将继承 Axios 的所有方法,并允许在发起请求时合并新的配置。
```javascript
const instance = axios.create({
baseURL: 'https://some-domain.com/api/',
timeout: 1000,
headers: {'X-Custom-Header': 'foobar'}
});
```
--------------------------------
### POST Request with FormData API (Node.js)
Source: https://www.axios-http.cn/docs/multipart
Shows how to create and send multipart/form-data requests in a Node.js environment using the FormData API and external packages for file handling.
```APIDOC
## POST /api/upload
### Description
Sends a file and other form data using the FormData API in Node.js, requiring a package like `formdata-node` for file handling.
### Method
POST
### Endpoint
https://example.com
### Parameters
#### Request Body
- **my_field** (string) - Required - A sample form field.
- **my_buffer** (Blob) - Required - A Blob object.
- **my_file** (File) - Required - The file to upload.
### Request Example (with formdata-node)
```javascript
import axios from 'axios';
import { fileFromPath } from 'formdata-node/file-from-path';
const form = new FormData();
form.append('my_field', 'my value');
form.append('my_buffer', new Blob(['some content']));
form.append('my_file', await fileFromPath('/foo/bar.jpg'));
axios.post('https://example.com', form);
```
### Response
#### Success Response (200)
- **status** (string) - Upload status.
#### Response Example
```json
{
"status": "success"
}
```
```
--------------------------------
### POST Request with FormData API (Browser)
Source: https://www.axios-http.cn/docs/multipart
Demonstrates how to use the browser's FormData API to construct and send a multipart/form-data POST request with Axios.
```APIDOC
## POST /api/upload
### Description
Sends a file and other form data using the browser's FormData API.
### Method
POST
### Endpoint
https://example.com
### Parameters
#### Request Body
- **my_field** (string) - Required - A sample form field.
- **my_buffer** (Blob) - Required - A Blob object.
- **my_file** (File) - Required - The file selected by the user.
### Request Example
```javascript
const form = new FormData();
form.append('my_field', 'my value');
form.append('my_buffer', new Blob([1,2,3]));
form.append('my_file', fileInput.files[0]);
axios.post('https://example.com', form)
```
### Response
#### Success Response (200)
- **message** (string) - Confirmation message.
#### Response Example
```json
{
"message": "File uploaded successfully"
}
```
```
--------------------------------
### Cancel Requests using AbortController
Source: https://www.axios-http.cn/docs/cancellation
Demonstrates how to use the standard AbortController API to cancel Axios requests. This is the recommended approach for versions 0.22.0 and later.
```javascript
const controller = new AbortController();
axios.get('/foo/bar', {
signal: controller.signal
}).then(function(response) {
//...
});
// 取消请求
controller.abort()
```
--------------------------------
### Axios Request Method Aliases
Source: https://www.axios-http.cn/docs/api_intro
Lists the available alias methods for common HTTP request types, simplifying request creation.
```APIDOC
## Axios Request Aliases
### Description
Axios provides convenient alias methods for all supported HTTP request methods, allowing for more concise code.
### Available Aliases
- **axios.request(config)**: The base method for making requests.
- **axios.get(url[, config])**: Makes a GET request.
- **axios.delete(url[, config])**: Makes a DELETE request.
- **axios.head(url[, config])**: Makes a HEAD request.
- **axios.options(url[, config])**: Makes an OPTIONS request.
- **axios.post(url[, data[, config]])**: Makes a POST request.
- **axios.put(url[, data[, config]])**: Makes a PUT request.
- **axios.patch(url[, data[, config]])**: Makes a PATCH request.
- **axios.postForm(url[, data[, config]])**: Makes a POST request with `Content-Type: application/x-www-form-urlencoded`.
- **axios.putForm(url[, data[, config]])**: Makes a PUT request with `Content-Type: application/x-www-form-urlencoded`.
- **axios.patchForm(url[, data[, config]])**: Makes a PATCH request with `Content-Type: application/x-www-form-urlencoded`.
### Note
When using these alias methods, you do not need to specify the `url`, `method`, or `data` properties within the `config` object, as they are implicitly handled by the alias.
```
--------------------------------
### POST Form with FileList
Source: https://www.axios-http.cn/docs/multipart
Demonstrates the convenience of directly passing a FileList object to `axios.postForm` for uploading multiple files.
```APIDOC
## POST /api/upload_files
### Description
Uploads multiple files directly using `axios.postForm` by passing a `FileList` object, where all files are sent with the default field name `files[]`.
### Method
POST
### Endpoint
https://httpbin.org/post
### Parameters
#### Request Body
- **files[]** (FileList) - Required - A FileList object containing the files to upload.
### Request Example
```javascript
// Assuming document.querySelector('#fileInput').files returns a FileList
await axios.postForm('https://httpbin.post', document.querySelector('#fileInput').files);
```
### Response
#### Success Response (200)
- **files** (object) - An object containing the uploaded files.
#### Response Example
```json
{
"files": {
"files[]": [
"...file content 1...",
"...file content 2..."
]
}
}
```
```
--------------------------------
### Submit HTML Form as JSON
Source: https://www.axios-http.cn/docs/post_example
Demonstrates how to capture an HTML form element and submit it as a JSON payload using Axios. It requires setting the Content-Type header to application/json.
```javascript
const {data} = await axios.post('/user', document.querySelector('#my-form'), {
headers: {
'Content-Type': 'application/json'
}
})
```
--------------------------------
### Handling Axios Errors
Source: https://www.axios-http.cn/docs/handling_errors
Demonstrates how to handle errors in Axios requests, including checking for response data, request objects, and general error messages.
```APIDOC
## Error Handling in Axios
### Description
Axios provides a robust way to handle errors using the .catch() method. You can inspect the error object to determine if the server responded with an error status, if the request was made but no response received, or if the request setup failed.
### Request Example
```javascript
axios.get('/user/12345')
.catch(function (error) {
if (error.response) {
// Server responded with status code outside 2xx range
console.log(error.response.data);
} else if (error.request) {
// Request made but no response received
console.log(error.request);
} else {
// Error setting up the request
console.log('Error', error.message);
}
});
```
```
--------------------------------
### 在 Node.js 中使用 querystring 和 URLSearchParams 编码请求体
Source: https://www.axios-http.cn/docs/urlencoded
介绍了在 Node.js 环境下利用内置的 querystring 模块或 url 模块中的 URLSearchParams 处理表单数据编码。
```javascript
const querystring = require('querystring');
axios.post('http://something.com/', querystring.stringify({ foo: 'bar' }));
```
```javascript
const url = require('url');
const params = new url.URLSearchParams({ foo: 'bar' });
axios.post('http://something.com/', params.toString());
```
--------------------------------
### Hybrid Request Cancellation
Source: https://www.axios-http.cn/docs/cancellation
Illustrates how to use both AbortController and CancelToken simultaneously during the transition period.
```javascript
const controller = new AbortController();
const CancelToken = axios.CancelToken;
const source = CancelToken.source();
axios.get('/user/12345', {
cancelToken: source.token,
signal: controller.signal
}).catch(function (thrown) {
if (axios.isCancel(thrown)) {
console.log('Request canceled', thrown.message);
} else {
// 处理错误
}
});
// 取消请求
source.cancel('Operation canceled by the user.');
controller.abort();
```
--------------------------------
### POST Request with FormData and form-data package (Node.js < v1.3.0)
Source: https://www.axios-http.cn/docs/multipart
Illustrates how to send multipart/form-data requests in older Node.js versions of Axios (< v1.3.0) using the `form-data` package.
```APIDOC
## POST /api/upload
### Description
Sends a file and other form data using the `form-data` package for Node.js environments with Axios versions prior to v1.3.0.
### Method
POST
### Endpoint
https://example.com
### Parameters
#### Request Body
- **my_field** (string) - Required - A sample form field.
- **my_buffer** (Buffer) - Required - A Node.js Buffer.
- **my_file** (Stream) - Required - A readable stream for the file.
### Request Example
```javascript
const FormData = require('form-data');
const fs = require('fs');
const form = new FormData();
form.append('my_field', 'my value');
form.append('my_buffer', new Buffer(10)); // Example buffer
form.append('my_file', fs.createReadStream('/foo/bar.jpg'));
axios.post('https://example.com', form, {
headers: form.getHeaders()
});
```
### Response
#### Success Response (200)
- **message** (string) - Server response message.
#### Response Example
```json
{
"message": "Upload complete"
}
```
```
--------------------------------
### 使用 FormData API 发起 Multipart 请求
Source: https://www.axios-http.cn/docs/multipart
展示在浏览器和 Node.js 环境中手动创建 FormData 对象并使用 Axios 发送请求的方法。Node.js 环境中可能需要第三方库如 formdata-node 或 form-data 来处理文件流。
```JavaScript (Browser)
const form = new FormData();
form.append('my_field', 'my value');
form.append('my_buffer', new Blob([1,2,3]));
form.append('my_file', fileInput.files[0]);
axios.post('https://example.com', form);
```
```JavaScript (Node.js)
import axios from 'axios';
const form = new FormData();
form.append('my_field', 'my value');
form.append('my_buffer', new Blob(['some content']));
axios.post('https://example.com', form);
```
--------------------------------
### FormData Serialization Options
Source: https://www.axios-http.cn/docs/multipart
Details the advanced configuration options for Axios's FormData serializer, including custom visitors, dot notation, meta tokens, and index handling.
```APIDOC
## POST /api/submit_custom
### Description
Provides advanced options to customize FormData serialization, such as using custom visitor functions, dot notation for nested objects, meta tokens for JSON parsing hints, and controlling array index formatting.
### Method
POST
### Endpoint
https://httpbin.org/post
### Parameters
#### Query Parameters
- **config.formSerializer** (object) - Optional - Configuration object for the form serializer.
- **visitor** (Function) - Optional - Custom function to handle data serialization.
- **dots** (boolean) - Optional - Use dot notation for nested objects (default: false).
- **metaTokens** (boolean) - Optional - Add meta tokens for JSON parsing (default: true).
- **indexes** (null|false|true) - Optional - Control array index formatting (default: false).
### Request Example (with custom options)
```javascript
import axios from 'axios';
import fs from 'fs';
const obj = {
x: 1,
arr: [1, 2, 3],
users: [{name: 'Peter', surname: 'Griffin'}]
};
axios.post('https://httpbin.org/post', obj, {
headers: {
'Content-Type': 'multipart/form-data'
},
formSerializer: {
dots: true, // Use dot notation for arrays/objects
metaTokens: false, // Disable meta tokens
indexes: true // Use indexed array notation
}
}).then(({data}) => console.log(data));
```
### Response
#### Success Response (200)
- **form** (object) - The serialized form data.
#### Response Example
```json
{
"form": {
"x": "1",
"arr.0": "1",
"arr.1": "2",
"arr.2": "3",
"users[0][name]": "Peter",
"users[0][surname]": "Griffin"
}
}
```
```
--------------------------------
### Handle HTTP Errors with Axios
Source: https://www.axios-http.cn/docs/handling_errors
Demonstrates how to catch and categorize errors based on whether a response was received, if the request was made, or if an internal error occurred. It accesses response data, status, and headers when available.
```javascript
axios.get('/user/12345')
.catch(function (error) {
if (error.response) {
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.headers);
} else if (error.request) {
console.log(error.request);
} else {
console.log('Error', error.message);
}
console.log(error.config);
});
```
--------------------------------
### Customizing Status Validation
Source: https://www.axios-http.cn/docs/handling_errors
How to use the validateStatus configuration option to define which HTTP status codes should resolve or reject the promise.
```APIDOC
## Customizing Status Validation
### Description
By default, Axios throws an error for any status code outside the 2xx range. You can override this behavior using the `validateStatus` configuration option.
### Request Body
- **validateStatus** (function) - Optional - A function that returns true if the status code should resolve the promise, or false to reject it.
### Request Example
```javascript
axios.get('/user/12345', {
validateStatus: function (status) {
return status < 500; // Resolve only if status code is less than 500
}
});
```
```
--------------------------------
### POST Request with axios.postForm (Browser)
Source: https://www.axios-http.cn/docs/multipart
Utilizes the `axios.postForm` convenience method for sending multipart/form-data requests, simplifying FormData handling.
```APIDOC
## POST /api/upload
### Description
Sends form data using the `axios.postForm` method, which automatically handles FormData serialization.
### Method
POST
### Endpoint
https://httpbin.org/post
### Parameters
#### Request Body
- **my_field** (string) - Required - A sample form field.
- **my_buffer** (Blob) - Required - A Blob object.
- **my_file** (FileList) - Required - A FileList object containing files.
### Request Example
```javascript
axios.postForm('https://httpbin.org/post', {
my_field: 'my value',
my_buffer: new Blob([1,2,3]),
my_file: fileInput.files // FileList will be unwrapped as separate fields
});
```
### Response
#### Success Response (200)
- **json** (object) - The parsed form data.
#### Response Example
```json
{
"json": {
"my_field": "my value",
"my_buffer": "...",
"my_file": "..."
}
}
```
```
--------------------------------
### Axios Request Configuration Object
Source: https://www.axios-http.cn/docs/req_config
This JavaScript object demonstrates the comprehensive configuration options available for making Axios HTTP requests. It covers essential settings like URL, method, baseURL, data transformations, headers, parameters, request body, timeouts, authentication, and response handling. It's a reference for customizing requests.
```javascript
{
// `url` is the server URL that will be used for the request
url: '/user',
// `method` is the request method to use when making the request
method: 'get', // default is 'get'
// `baseURL` will be prepended to `url` unless `url` is a absolute URL.
// It can be convenient to set a baseURL on the instance rather than the config
baseURL: 'https://some-domain.com/api/',
// `transformRequest` allows you to transform request data before it's sent to the server
// It can only work for config.transformRequest, which is applied to the data
// right before it gets sent.
transformRequest: [function (data, headers) {
// Do something with data
return data;
}],
// `transformResponse` allows you to transform response data before 7th is passed to the then/catch method
transformResponse: [function (data) {
// Do something with response 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 setting that allows you to override the default serializer for params
paramsSerializer: {
//encode?: (param: string): string => { /* ... */ },
//serialize?: (params: Record, options?: ParamsSerializerOptions) => string,
indexes: false // example: [1, 2, 3]
},
// `data` is the data to be sent as the request body
// Only applicable for config.method used with 'PUT', 'POST', 'DELETE and 'PATCH'
data: {
firstName: 'Fred'
},
// `timeout` specifies the number of milliseconds either for request timeout or response timeout
// If set to 0 (default) a new timeout is never created. Meaning there is no timeout
timeout: 1000, // default is `0` which means no timeout
// `withCredentials` indicates whether the request should be made using credentials
withCredentials: false, // default
// `adapter` allows you to custom data handling
adapter: function (config) {
/* ... */
},
// `auth` HTTP Basic Authentication
auth: {
username: 'janedoe',
password: 's00pers3cret'
},
// `responseType` indicates the type of data that the server will respond with
// Options are 'arraybuffer', 'document', 'json', 'text', 'stream'
responseType: 'json', // default
// `responseEncoding` indicates encoding for decoding response data (Node.js only)
responseEncoding: 'utf8', // default
// `xsrfCookieName` is the name of the cookie to be used for getting the xsrf token
xsrfCookieName: 'XSRF-TOKEN', // default
// `xsrfHeaderName` is the name of the http header to keep xsrf token
xsrfHeaderName: 'X-XSRF-TOKEN', // default
// `onUploadProgress` allows handling of progress events for uploads
onUploadProgress: function (progressEvent) {
// Do something with upload progress
},
// `onDownloadProgress` allows handling of progress events for downloads
onDownloadProgress: function (progressEvent) {
// Do something with download progress
},
// `maxContentLength` defines the maximum size in bytes of the http response content for Node.js
maxContentLength: 2000,
// `maxBodyLength` (Node only) defines the maximum size in bytes of the http request content
maxBodyLength: 2000,
// `validateStatus` defines whether a response needs to be given a then or catch
validateStatus: function (status) {
return status >= 200 && status < 300; // default
},
// `maxRedirects` defines the maximum number of redirects Axios will follow for Node.js
maxRedirects: 5, // default
// `socketPath` defines the UNIX socket to use for requests in Node.js
socketPath: null, // default
// `httpAgent` and `httpsAgent` define custom agents for http and https requests in Node.js
httpAgent: new http.Agent({ keepAlive: true }),
httpsAgent: new https.Agent({ keepAlive: true }),
// `proxy` defines the hostname, port and protocol of the proxy server
proxy: {
protocol: 'https',
host: '127.0.0.1',
port: 9000,
auth: {
username: 'mikeymike',
password: 'rapunz3l'
}
},
// `cancelToken` allows you to cancel a request
cancelToken: new CancelToken(function (cancel) { /* ... */ }),
// `decompress` indicates whether or not the response body should be decompressed
decompress: true // default
}
```
--------------------------------
### Add Request and Response Interceptors
Source: https://www.axios-http.cn/docs/interceptors
Demonstrates how to register interceptors for global Axios requests and responses. These functions allow for modifying configurations or handling errors before the promise is settled.
```javascript
// 添加请求拦截器
axios.interceptors.request.use(function (config) {
// 在发送请求之前做些什么
return config;
}, function (error) {
// 对请求错误做些什么
return Promise.reject(error);
});
// 添加响应拦截器
axios.interceptors.response.use(function (response) {
// 2xx 范围内的状态码都会触发该函数。
// 对响应数据做点什么
return response;
}, function (error) {
// 超出 2xx 范围的状态码都会触发该函数。
// 对响应错误做点什么
return Promise.reject(error);
});
```
--------------------------------
### Customize Status Code Validation
Source: https://www.axios-http.cn/docs/handling_errors
Shows how to use the validateStatus configuration option to define which HTTP status codes should trigger a promise rejection. This allows for granular control over error handling logic.
```javascript
axios.get('/user/12345', {
validateStatus: function (status) {
return status < 500;
}
})
```
--------------------------------
### Automatic FormData Serialization
Source: https://www.axios-http.cn/docs/multipart
Explains and demonstrates Axios's automatic serialization of plain objects into FormData when the 'Content-Type' is 'multipart/form-data'.
```APIDOC
## POST /api/submit
### Description
Axios automatically serializes plain JavaScript objects into FormData when the `Content-Type` header is set to `multipart/form-data`, simplifying complex data structures and file uploads.
### Method
POST
### Endpoint
https://httpbin.org/post
### Parameters
#### Request Body
- **user** (object) - Required - An object containing user details. Will be JSON stringified by default.
- **file** (Stream) - Required - A readable stream for the file to upload.
### Request Example
```javascript
import axios from 'axios';
import fs from 'fs'; // Assuming Node.js environment for fs
axios.post('https://httpbin.org/post', {
user: {
name: 'Dmitriy'
},
file: fs.createReadStream('/foo/bar.jpg')
}, {
headers: {
'Content-Type': 'multipart/form-data'
}
}).then(({data}) => console.log(data));
```
### Response
#### Success Response (200)
- **form** (object) - The parsed multipart form data.
#### Response Example
```json
{
"form": {
"user": "{\"name\": \"Dmitriy\"}",
"file": "..."
}
}
```
```
--------------------------------
### Set Global Axios Defaults
Source: https://www.axios-http.cn/docs/config_defaults
Configure global default settings for Axios that will apply to every request made. This includes setting the base URL, common authorization headers, and content types for POST requests. No external dependencies are required beyond the Axios library itself.
```javascript
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';
```
--------------------------------
### 在 Node.js 中使用 FormData 处理文件上传
Source: https://www.axios-http.cn/docs/urlencoded
演示了如何在 Node.js 中使用 form-data 库构建表单数据,并通过手动设置请求头或使用拦截器确保正确发送 multipart/form-data。
```javascript
const FormData = require('form-data');
const form = new FormData();
form.append('my_field', 'my value');
form.append('my_buffer', new Buffer(10));
form.append('my_file', fs.createReadStream('/foo/bar.jpg'));
axios.post('https://example.com', form, { headers: form.getHeaders() });
```
```javascript
axios.interceptors.request.use(config => {
if (config.data instanceof FormData) {
Object.assign(config.headers, config.data.getHeaders());
}
return config;
});
```
--------------------------------
### Request Cancellation via AbortController
Source: https://www.axios-http.cn/docs/cancellation
The recommended way to cancel requests in Axios v0.22.0+ using the standard AbortController API.
```APIDOC
## AbortController Request Cancellation
### Description
Uses the standard browser AbortController to signal and cancel an ongoing HTTP request.
### Method
GET/POST/PUT/DELETE
### Parameters
#### Request Config
- **signal** (AbortSignal) - Required - The signal object from an AbortController instance.
### Request Example
```javascript
const controller = new AbortController();
axios.get('/foo/bar', {
signal: controller.signal
});
// To cancel:
controller.abort();
```
```
--------------------------------
### 使用 Axios 自动序列化 Multipart 数据
Source: https://www.axios-http.cn/docs/multipart
演示 Axios 如何自动将普通对象序列化为 FormData,支持通过 headers 设置 Content-Type 或使用 postForm 别名方法。该功能支持通过 config.formSerializer 配置序列化规则。
```JavaScript
import axios from 'axios';
axios.post('https://httpbin.org/post', {
user: { name: 'Dmitriy' },
file: fs.createReadStream('/foo/bar.jpg')
}, {
headers: { 'Content-Type': 'multipart/form-data' }
}).then(({data})=> console.log(data));
```
```JavaScript (postForm)
await axios.postForm('https://httpbin.org/post', document.querySelector('#fileInput').files);
```
--------------------------------
### Serialize Error Objects to JSON
Source: https://www.axios-http.cn/docs/handling_errors
Illustrates the use of the toJSON method on an error object to retrieve a serialized representation of the HTTP error for logging or debugging purposes.
```javascript
axios.get('/user/12345')
.catch(function (error) {
console.log(error.toJSON());
});
```