axio 参数配置

分析Config

配置参数很多,我们一个一个来了解它们

  • url —— 用来向服务器发送请求的url
  • method —— 请求方法,默认是GET方法
  • baseURL —— 基础URL路径,假如url不是绝对路径,如https://some-domain.com/api/v1/login?name=jack,那么向服务器发送请求的URL将会是baseURL + url
  • transformRequest —— transformRequest方法允许在请求发送到服务器之前修改该请求,此方法只适用于PUTPOSTPATCH方法中。而且,此方法最后必须返回一个string、ArrayBuffer或者Stream。
  • transformResponse —— transformResponse方法允许在数据传递到then/catch之前修改response数据。此方法最后也要返回数据。
  • headers —— 发送自定义Headers头文件,头文件中包含了http请求的各种信息。
  • params —— params是发送请求的查询参数对象,对象中的数据会被拼接成url?param1=value1&param2=value2
  • paramsSerializer —— params参数序列化器。
  • data —— data是在发送POSTPUT或者PATCH请求的数据对象。
  • timeout —— 请求超时设置,单位为毫秒
  • withCredentials —— 表明是否有跨域请求需要用到证书
  • adapter —— adapter允许用户处理更易于测试的请求。返回一个Promise和一个有效的response
  • auth —— auth表明提供凭证用于完成http的身份验证。这将会在headers中设置一个Authorization授权信息。自定义Authorization授权要设置在headers中。
  • responseType —— 表示服务器将返回响应的数据类型,有arraybufferblobdocumentjsontextstream这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对象。

猜你喜欢

转载自blog.csdn.net/qq_36838191/article/details/80872837