vue下axios以及vue-resource的对比使用

写在前面:vue2.0之后,就不再对vue-resource更新,而是推荐使用axios(注意了注意了)。axios可同时在浏览器和 Node.js 中使用,相比之下,axios虽然体积较大,但是功能用法也是很全面的,推荐使用。

一、vue-Resource

npm链接地址: https://www.npmjs.com/package/vue-resource

(1)特点:
  1. 支持Promise API和URI Templates
  2. 支持request和response的请求拦截器
  3. 支持主流浏览器,IE9+
  4. 支持vue1.0及vue2.0
  5. 打包体积小
(2)应用代码举例:
// 1、应用在代码中,get与post写法一致
this.$http.get('/someUrl',[body], [options]).then((response) => {
  // 响应成功回调
}, (response) => {
  // 响应错误回调
});


// 2、添加拦截器
Vue.http.interceptors.push((request, next) => { 
   // console.log(this)//此处this为请求所在页面的Vue实例 
 	// modify request 
 	request.method = 'POST';//在请求之前可以进行一些预处理和配置,也可以设置一些header等
 	// continue to next interceptor 
   next((response) => {
   		//在响应之后传给then之前对response进行修改和逻辑判断。页面中任何一次http请求都会先调用此处方法 
    	response.body = '...'; 
    	return response; 
 	}); 
});

通常拦截器在前端的使用:
添加统一的request参数;
处理统一的responseErr,也或者根据token来判断用户状态。

vue-resource拦截器参考链接:https://blog.csdn.net/qq_41882147/article/details/80743730

二、axios

npm链接地址:https://www.npmjs.com/package/axios

(1)特点:
  1. 从浏览器生成XMLHttpRequests
  2. 从node.js发出http请求
  3. 支持Promise API
  4. 拦截请求和响应
  5. 转换请求和响应数据
  6. 取消请求
  7. 自动转换JSON数据
  8. 客户端支持防范XSRF
  9. 支持主流浏览器、IE8.1+。
(2)应用代码举例:
// 1、正常单个请求,get与post一致
axios.get(url, [body], [options]).then(function (response) {
    console.log(response);
  }).catch(function (error) {
    console.log(error);
  }).then(function () {
    // always executed
  });
  
// 结合es6新语法async/await,添加keyword 'async'
async function getUser() {
  try {
    const response = await axios.get('/user?ID=12345');
    console.log(response);
  } catch (error) {
    console.error(error);
  }
}

// 2、多个axios请求集合
function getUserAccount() {
  return axios.get('/user/12345');
}
 
function getUserPermissions() {
  return axios.get('/user/12345/permissions');
}
 
axios.all([getUserAccount(), getUserPermissions()])
  .then(axios.spread(function (acct, perms) {
    // Both requests are now complete
  }));
  
// 3、axios的API写法:(axios的API符合RESTful架构)
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]])

// 4、axios处理并发请求

// 5、自定义创建新的axios实例
const instance = axios.create({
  baseURL: 'https://some-domain.com/api/',
  timeout: 1000,
  headers: {'X-Custom-Header': 'foobar'}
}); // 通常在main.js中配置,也可以根据自己的实际需要配置
// axios的实例方法
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])

(3)请求配置(其中proxy的代理配置是在项目中实际应用次数较多较实用的配置)
{
  url: '/user',
 
  method: 'get', // default
 
  baseURL: 'https://some-domain.com/api/',
 
  // `transformRequest`允许在将请求数据发送到服务器之前对其进行更改。这仅适用于请求方法'PUT','POST','PATCH'和'DELETE'。数组中的最后一个函数必须返回一个字符串 或者Buffer,ArrayBuffer,FormData或Stream的实例。可以修改headers对象。
  transformRequest: [function (data, headers) {
    // Do whatever you want to transform the data
    return data;
  }],
 
  // `transformResponse`允许在将响应数据传递给then / catch之前对响应数据进行更改
  transformResponse: [function (data) {
    // Do whatever you want to transform the data 
    return data;
  }],
 
  headers: {'X-Requested-With': 'XMLHttpRequest'},
 
  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'})
  },
 
  // 仅适用于请求方法'PUT','POST'和'PATCH'
   //当没有设置`transformRequest`时,必须是以下类型之一:
   //  - 字符串,普通对象,ArrayBuffer,ArrayBufferView,URLSearchParams
   //  - 仅限浏览器:FormData,File,Blob
   //  - 仅限节点:流,缓冲区
  data: {
    firstName: 'Fred'
  },
 
  timeout: 1000, // default is `0` (no timeout)
 
  // `withCredentials`表示是否应使用凭据进行跨站点访问控制请求
  withCredentials: false, // default
 
  // `adapter`允许自定义处理请求,使测试更容易。 返回一个promise并提供一个有效的响应(参见lib / adapters / README.md)。
  adapter: function (config) {
    /* ... */
  },
 
  // `auth`表示应该使用HTTP Basic auth,并提供凭据。
   //这将设置一个`Authorization`标题,覆盖任何现有标题
   //使用`headers`设置的`Authorization`自定义标题。
   //请注意,只有HTTP Basic auth可以通过此参数进行配置。
   //对于Bearer令牌等,请改用“Authorization”自定义标头。
  auth: {
    username: 'janedoe',
    password: 's00pers3cret'
  },
 
  // `responseType`表示服务器将使用选项响应的数据类型:'arraybuffer','document','json','text','stream'仅限浏览器:'blob'
  responseType: 'json', // default
 
  //`responseEncoding`表示用于解码响应的编码
   //注意:忽略“stream”或“客户端”请求的“responseType”
  responseEncoding: 'utf8', // default
 
  // `xsrfCookieName`是用作xsrf标记值的cookie的名称
  xsrfCookieName: 'XSRF-TOKEN', // default
 
  // `xsrfHeaderName`是带有xsrf标记值的http标头的名称
  xsrfHeaderName: 'X-XSRF-TOKEN', // default
 
  // `onUploadProgress`允许处理上传的进度事件
  onUploadProgress: function (progressEvent) {
    // Do whatever you want with the native progress event
  },
 
  // `onDownloadProgress`允许处理下载的进度事件
  onDownloadProgress: function (progressEvent) {
    // 使用本机进度事件执行任何操作
  },
 
  // `maxContentLength`定义了允许的以字节为单位的http响应内容的最大大小
  maxContentLength: 2000,
 
  // `validateStatus`定义是否解析或拒绝给定HTTP响应状态代码的promise。 如果`validateStatus`返回`true`(或设置为`null`或`undefined`),则将解决promise; 否则,承诺将被拒绝。
  validateStatus: function (status) {
    return status >= 200 && status < 300; // default
  },
 
  // `maxRedirects`定义了node.js中要遵循的最大重定向数。如果设置为0,则不会遵循重定向。
  maxRedirects: 5, // default
 
  //`socketPath`定义了一个在node.js中使用的UNIX Socket。例如 '/var/run/docker.sock'将请求发送到docker守护程序。只能指定`socketPath`或`proxy`。如果同时指定了两者,则使用`socketPath`。
  socketPath: null, // default
 
  // `httpAgent`和`httpsAgent`分别定义了在node.js中执行http和https请求时使用的自定义代理。 这允许添加类似`keepAlive`的选项,默认情况下不启用。
  httpAgent: new http.Agent({ keepAlive: true }),
  httpsAgent: new https.Agent({ keepAlive: true }),
 
  // 'proxy'定义代理服务器的主机名和端口。 您还可以使用传统的`http_proxy`和`https_proxy`环境变量来定义代理。 如果要为代理配置使用环境变量,还可以将“no_proxy”环境变量定义为不应代理的以逗号分隔的域列表。 使用`false`来禁用代理,忽略环境变量。 `auth`表示应该使用HTTP Basic auth连接到代理,并提供凭据。 这将设置一个`Proxy-Authorization`头,覆盖你使用`headers`设置的任何现有`Proxy-Authorization`自定义头。
  proxy: {
    host: '127.0.0.1',
    port: 9000,
    auth: {
      username: 'mikeymike',
      password: 'rapunz3l'
    }
  },
 
  // `cancelToken` 指定了一个可以用来取消请求的cancel token
  cancelToken: new CancelToken(function (cancel) {
  })
}
(4)响应概要
{
  // `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
  // All header names are lower cased
  headers: {},
 
  // `config` is the config that was provided to `axios` for the request
  config: {},
 
  // `request` is the request that generated this response
  // It is the last ClientRequest instance in node.js (in redirects)
  // and an XMLHttpRequest instance the browser
  request: {}
}
(5)默认配置
// 1、全局默认配置
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';
// 2、特定实例配置
const instance = axios.create({
  baseURL: 'https://api.example.com'
});

// 在实例创建之后改变默认配置
instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;
(6)拦截器
// Add a request interceptor
axios.interceptors.request.use(function (config) {
    // Do something before request is sent
    return config;
  }, function (error) {
    // Do something with request error
    return Promise.reject(error);
  });
 
// Add a response interceptor
axios.interceptors.response.use(function (response) {
    // Do something with response data
    return response;
  }, function (error) {
    // Do something with response error
    return Promise.reject(error);
  });

// 移除一个拦截器
const myInterceptor = axios.interceptors.request.use(function () {/*...*/});
axios.interceptors.request.eject(myInterceptor);
// 添加一个拦截器
const instance = axios.create();
instance.interceptors.request.use(function () {/*...*/});

(7)取消请求
// 1、你可以用一个cancel token取消请求
const CancelToken = axios.CancelToken;
const source = CancelToken.source();
 
axios.get('/user/12345', {
  cancelToken: source.token
}).catch(function (thrown) {
  if (axios.isCancel(thrown)) {
    console.log('Request canceled', thrown.message);
  } else {
    // handle error
  }
});
 
axios.post('/user/12345', {
  name: 'new name'
}, {
  cancelToken: source.token
})
 
// cancel the request (the message parameter is optional)
source.cancel('Operation canceled by the user.');


// 2、通过将执行程序函数传递给CancelToken构造函数来创建取消令牌
const CancelToken = axios.CancelToken;
let cancel;
 
axios.get('/user/12345', {
  cancelToken: new CancelToken(function executor(c) {
    // An executor function receives a cancel function as a parameter
    cancel = c;
  })
});
 
// cancel the request
cancel();
(8)使用"application/x-www-form-urlencoded"形式

通常,axios会将JavaScript对象转为json。为了使用"application/x-www-form-urlencoded"形式,你可以使用下面的办法。

// 1、浏览器
// 1.1、使用URLSearchParams API(但是要注意不是被所有浏览器都支持的)
const params = new URLSearchParams();
params.append('param1', 'value1');
params.append('param2', 'value2');
axios.post('/foo', params);
// 1.2、使用qs的stringify来encode数据
const qs = require('qs');
axios.post('/foo', qs.stringify({ 'bar': 123 }));
// 1.3、es6的办法
import qs from 'qs';
const data = { 'bar': 123 };
const options = {
  method: 'POST',
  headers: { 'content-type': 'application/x-www-form-urlencoded' },
  data: qs.stringify(data),
  url,
};
axios(options);

// 2、node.js中,使用querystring模块或者qs库
const querystring = require('querystring');
axios.post('http://something.com/', querystring.stringify({ foo: 'bar' }));
(9)可包含typescript定义
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值