分析Config
配置参数很多,我们一个一个来了解它们
- url —— 用来向服务器发送请求的url
- method —— 请求方法,默认是
GET
方法 - baseURL —— 基础URL路径,假如
url
不是绝对路径,如https://some-domain.com/api/v1/login?name=jack
,那么向服务器发送请求的URL将会是baseURL + url
。 - transformRequest ——
transformRequest
方法允许在请求发送到服务器之前修改该请求,此方法只适用于PUT
、POST
和PATCH
方法中。而且,此方法最后必须返回一个string、ArrayBuffer或者Stream。 - transformResponse ——
transformResponse
方法允许在数据传递到then/catch之前修改response
数据。此方法最后也要返回数据。 - headers —— 发送自定义Headers头文件,头文件中包含了http请求的各种信息。
- params ——
params
是发送请求的查询参数对象,对象中的数据会被拼接成url?param1=value1¶m2=value2
。 - paramsSerializer ——
params
参数序列化器。 - data ——
data
是在发送POST
、PUT
或者PATCH
请求的数据对象。 - timeout —— 请求超时设置,单位为毫秒
- withCredentials —— 表明是否有跨域请求需要用到证书
- adapter ——
adapter
允许用户处理更易于测试的请求。返回一个Promise和一个有效的response - auth ——
auth
表明提供凭证用于完成http的身份验证。这将会在headers中设置一个Authorization
授权信息。自定义Authorization
授权要设置在headers
中。 - responseType —— 表示服务器将返回响应的数据类型,有
arraybuffer
、blob
、document
、json
、text
、stream
这6个类型,默认是json
类似数据。 - xsrfCookieName —— 用作 xsrf token 值的 cookie 名称
- xsrfHeaderName —— 带有 xsrf token 值 http head 名称
- onUploadProgress —— 允许在上传过程中的做一些操作
- onDownloadProgress —— 允许在下载过程中的做一些操作
- maxContentLength —— 定义了接收到的response响应数据的最大长度。
- validateStatus ——
validateStatus
定义了根据HTTP响应状态码决定是否接收或拒绝获取到的promise。如果validateStatus
返回true
(或设置为null
或undefined
),promise将被接收;否则,promise将被拒绝。 - maxRedirects ——
maxRedirects
定义了在node.js中redirect的最大值,如果设置为0,则没有redirect。 - httpAgent —— 定义在使用http请求时的代理
- httpsAgent —— 定义在使用https请求时的代理
- proxy ——
proxy
定义代理服务器的主机名和端口,auth
- cancelToken ——
cancelToken
定义一个cancel token
用于取消请求
Response
当我们ajax获取数据成功后会返回一个response对象,它包含了以下内容:
{
// `data` is the response that was provided by the server
data: {},
// `status` is the HTTP status code from the server response
status: 200, // `statusText` is the HTTP status message from the server response statusText: 'OK', // `headers` the headers that the server responded with headers: {}, // `config` is the config that was provided to `axios` for the request config: {} }
response是通过promise的then
方法来获取,具体使用方法如下:
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); });
相对的,我们有时也会出现ajax报错,此时就会到我们的catch
中去捕获异常error
对象。