axios请求使用指南

Axio是一个基于Promise的网络请求库,同时适配于浏览器端和服务端(nodejs)。在服务端它使用原生 node.js http 模块, 而在客户端 (浏览端) 则使用 XMLHttpRequests。本文介绍axios的常规使用方法以及axios的主要API功能。


axios请求使用指南


安装

支持各类工具安装使用:

$ npm i axios
$ yarn add axios
$ pnpm i axios

也可以直接通过cdn加载axios

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

请求示例

axios内置请求方法:request、get、delete、head、options、put、patch、put方法进行对应方法请求,也可以通过axios配置config进行配置请求:

// axios配置请求
axios
({
method
:'get',
url
:'http://bit.ly/2mTM3nY',
responseType
:'stream'
})
.then(function(response) {
response
.data.pipe(fs.createWriteStream('ada_lovelace.jpg'))
});


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请求示例来了解如何使用axios发起一个请求:

1、发起get请求

// 为给定 id的 user 创建请求
axios
.get('/user?id=12345')
.then(function (response) {
console
.log(response);
})
.catch(function (error) {
console
.log(error);
});

2、发起post请求

axios.post('/user', {
firstName
: 'Fred',
lastName
: 'Flintstone'
})
.then(function (response) {
console
.log(response);
})
.catch(function (error) {
console
.log(error);
});

3、发起put请求

const axios = require('axios');

// 设置请求的URL,以及需要更新的数据
const url = 'https://www.enjoytoday.cn/api/data';
const data = {
key
: 'value'
};

// 发起PUT请求
axios
.put(url, data)
.then(response => {
console
.log('PUT请求成功:', response);
})
.catch(error => {
console
.error('PUT请求出错:', error);
});

4、发起delete请求

const axios = require('axios');

// 发送DELETE请求
axios
.delete('https://www.enjoytoday.cn/resource')
.then(function (response) {
// 处理响应数据
console
.log(response.data);
})
.catch(function (error) {
// 处理错误情况
console
.log(error);
});

5、发起form-data请求

form-data请求,通常用于上传文件或提交表单数据。这是之前浏览器端设计的表单配置的模式,这里提供两种方式来进行,一种纯表单数据可以使用’application/x-www-form-urlencoded‘头部信息,一种需要上传文件,需要设置:’multipart/form-data‘ 头部信息。如上可总结两种方式进行form-data参数请求,这里以post方法为例

  • FormData对象参数上传

  • FormData对象上传 【也可以只是单独传参】

// 对象上传
const axios = require('axios'); // 引入axios库
axios
({
method
: 'post',
url
: 'http://example.com/login',
headers
: {'Content-Type': 'application/x-www-form-urlencoded'},
data
: {
username
: 'enjoytoday.cn',
password
: 'pass'
}
})
.then(function(response) {
console
.log('Response:', response);
})
.catch(function(error) {
console
.log('Error:', error);
});


// formData对象请求

const axios = require('axios'); // 引入axios库
const formData = new FormData()
formData
.append('username', 'enjoytoday.cn'); // 添加键值对
formData
.append('nickname', '胖蔡'); // 添加键值对
formData
.append('file', file); // 添加文件

// 发送POST请求
axios
.post('http://example.com/upload', formData, {
headers
: {
'Content-Type': 'multipart/form-data',
}
})
.then(response => {
console
.log('Success:', response.data);
})
.catch(error => {
console
.error('Error:', error);
});

配置与APIS

实例配置

常规的我们会通过创建一个axios示例配置一些公用配置,如:请求前缀、请求超时时间、共用请求头等,创建示例如下:

const instance: AxiosInstance = axios.create({
baseURL
,
timeout
: 60000,
headers
: { 'Content-Type': 'application/json;charset=UTF-8'},
})

创建配置的options,其支持配置属性如下:

export interface AxiosRequestConfig<D = any> {
url
?: string;
method
?: Method | string;
baseURL
?: string;
transformRequest
?: AxiosRequestTransformer | AxiosRequestTransformer[];
transformResponse
?: AxiosResponseTransformer | AxiosResponseTransformer[];
headers
?: (RawAxiosRequestHeaders & MethodsHeaders) | AxiosHeaders;
params?: any;
paramsSerializer
?: ParamsSerializerOptions | CustomParamsSerializer;
data
?: D;
timeout
?: Milliseconds;
timeoutErrorMessage
?: string;
withCredentials
?: boolean;
adapter
?: AxiosAdapterConfig | AxiosAdapterConfig[];
auth
?: AxiosBasicCredentials;
responseType
?: ResponseType;
responseEncoding
?: responseEncoding | string;
xsrfCookieName
?: string;
xsrfHeaderName
?: string;
onUploadProgress
?: (progressEvent: AxiosProgressEvent) => void;
onDownloadProgress
?: (progressEvent: AxiosProgressEvent) => void;
maxContentLength
?: number;
validateStatus
?: ((status: number) => boolean) | null;
maxBodyLength
?: number;
maxRedirects
?: number;
maxRate
?: number | [MaxUploadRate, MaxDownloadRate];
beforeRedirect
?: (options: Record<string, any>, responseDetails: {headers: Record<string, string>, statusCode: HttpStatusCode}) => void;
socketPath
?: string | null;
transport
?: any;
httpAgent
?: any;
httpsAgent
?: any;
proxy
?: AxiosProxyConfig | false;
cancelToken
?: CancelToken;
decompress
?: boolean;
transitional
?: TransitionalOptions;
signal
?: GenericAbortSignal;
insecureHTTPParser
?: boolean;
env
?: {
FormData?: new (...args: any[]) => object;
};
formSerializer
?: FormSerializerOptions;
family
?: AddressFamily;
lookup
?: ((hostname: string, options: object, cb: (err: Error | null, address: LookupAddress | LookupAddress[], family?: AddressFamily) => void) => void) |
((hostname: string, options: object) => Promise<[address: LookupAddressEntry | LookupAddressEntry[], family?: AddressFamily] | LookupAddress>);
withXSRFToken
?: boolean | ((config: InternalAxiosRequestConfig) => boolean | undefined);
}

改配置属性在发起请求时通用,若和axios实例已存在配置会自动覆盖,且发起请求的配置除了url是必须属性外,其他均为非必需属性。

全局配置

通过实例配置想要生效的话需要所有请求都是通过该实例发起的,也就是axios.create创建产生的对象,当我们想要对axios创建的所有对象均生效的话,我们可以通过配置axios.defaults来实现,配置如下:

axios.defaults.baseURL = 'https://www.enjoytoday.cn';
axios
.defaults.headers.common['Authorization'] = 'Authorization';
axios
.defaults.headers.post['Content-Type'] = 'application/json';

defautls支持所有AxiosRequestConfig的配置项。

拦截器

可以通过拦截器对网络请求体和请求返回数据进行拦截处理,如响应数据格式化,响应状态全局处理等,也可以对一些特殊请求场景进行差异化处理,如上传下载文件可以拦截请求配置对应请配置。

// 添加请求拦截器
axios
.interceptors.request.use(function (config) {
// 在发送请求之前做些什么
return config;
}, function (error) {
// 对请求错误做些什么
return Promise.reject(error);
});

// 添加响应拦截器
axios
.interceptors.response.use(function (response) {
// 对响应数据做点什么
return response;
}, function (error) {
// 对响应错误做点什么
return Promise.reject(error);
});

APIS

如下是一些axios请求支持的高级配置用法:

  • transformRequest:允许在向服务器发送前,修改请求数据,适用于’PUT’, ‘POST’ 和 ‘PATCH’ 这几个请求方法

  • transformResponse:在传递给 then/catch 前,允许修改响应数据

  • onUploadProgress:允许为上传处理进度事件

  • onDownloadProgress:为下载处理进度事件

更多全局配置如下:

{
// `url` 是用于请求的服务器 URL
url
: '/user',

// `method` 是创建请求时使用的方法
method
: 'get', // default

// `baseURL` 将自动加在 `url` 前面,除非 `url` 是一个绝对 URL。
// 它可以通过设置一个 `baseURL` 便于为 axios 实例的方法传递相对 URL
baseURL
: 'https://some-domain.com/api/',

// `transformRequest` 允许在向服务器发送前,修改请求数据
// 只能用在 'PUT', 'POST' 和 'PATCH' 这几个请求方法
// 后面数组中的函数必须返回一个字符串,或 ArrayBuffer,或 Stream
transformRequest
: [function (data, headers) {
// 对 data 进行任意转换处理
return data;
}],

// `transformResponse` 在传递给 then/catch 前,允许修改响应数据
transformResponse
: [function (data) {
// 对 data 进行任意转换处理
return data;
}],

// `headers` 是即将被发送的自定义请求头
headers
: {'X-Requested-With': 'XMLHttpRequest'},

// `params` 是即将与请求一起发送的 URL 参数
// 必须是一个无格式对象(plain object)或 URLSearchParams 对象
params: {
ID
: 12345
},

// `paramsSerializer` 是一个负责 `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` 是作为请求主体被发送的数据
// 只适用于这些请求方法 'PUT', 'POST', 和 'PATCH'
// 在没有设置 `transformRequest` 时,必须是以下类型之一:
// - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams
// - 浏览器专属:FormData, File, Blob
// - Node 专属: Stream
data
: {
firstName
: 'Fred'
},

// `timeout` 指定请求超时的毫秒数(0 表示无超时时间)
// 如果请求话费了超过 `timeout` 的时间,请求将被中断
timeout
: 1000,

// `withCredentials` 表示跨域请求时是否需要使用凭证
withCredentials
: false, // default

// `adapter` 允许自定义处理请求,以使测试更轻松
// 返回一个 promise 并应用一个有效的响应 (查阅 [response docs](#response-api)).
adapter
: function (config) {
/* ... */
},

// `auth` 表示应该使用 HTTP 基础验证,并提供凭据
// 这将设置一个 `Authorization` 头,覆写掉现有的任意使用 `headers` 设置的自定义 `Authorization`头
auth
: {
username
: 'janedoe',
password
: 's00pers3cret'
},

// `responseType` 表示服务器响应的数据类型,可以是 'arraybuffer', 'blob', 'document', 'json', 'text', 'stream'
responseType
: 'json', // default

// `responseEncoding` indicates encoding to use for decoding responses
// Note: Ignored for `responseType` of 'stream' or client-side requests
responseEncoding
: 'utf8', // default

// `xsrfCookieName` 是用作 xsrf token 的值的cookie的名称
xsrfCookieName
: 'XSRF-TOKEN', // default

// `xsrfHeaderName` is the name of the http header that carries the xsrf token value
xsrfHeaderName
: 'X-XSRF-TOKEN', // default

// `onUploadProgress` 允许为上传处理进度事件
onUploadProgress
: function (progressEvent) {
// Do whatever you want with the native progress event
},

// `onDownloadProgress` 允许为下载处理进度事件
onDownloadProgress
: function (progressEvent) {
// 对原生进度事件的处理
},

// `maxContentLength` 定义允许的响应内容的最大尺寸
maxContentLength
: 2000,

// `validateStatus` 定义对于给定的HTTP 响应状态码是 resolve 或 reject promise 。如果 `validateStatus` 返回 `true` (或者设置为 `null` 或 `undefined`),promise 将被 resolve; 否则,promise 将被 rejecte
validateStatus
: function (status) {
return status >= 200 && status < 300; // default
},

// `maxRedirects` 定义在 node.js 中 follow 的最大重定向数目
// 如果设置为0,将不会 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` 和 `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) {
})
}


原文始发于微信公众号(胖蔡话前端):axios请求使用指南

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/259187.html

(0)
土豆大侠的头像土豆大侠

相关推荐

发表回复

登录后才能评论
极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!