The difference between vue-resource and axios

resource-view

Vue.js is data-driven, which means we don't need to manipulate the DOM directly. If we don't need to use jQuery's DOM selectors, there's no need to import jQuery. vue-resource is a plugin for Vue.js that can initiate requests and process responses via XMLHttpRequest or JSONP. In other words, what $.ajax can do, the vue-resource plugin can do the same, and the vue-resource API is more concise. In addition, vue-resource also provides a very useful interceptor function. Using the interceptor can add some behaviors before and after the request, such as using the interceptor to display the loading interface during ajax requests.

vue-resource features

The vue-resource plugin has the following features:

  1. Small size
    vue-resource is very small, only about 12KB after compression, and only 4.5KB after gzip compression is enabled on the server, which is much smaller than jQuery.
  2. Supports mainstream browsers
    Like Vue.js, vue-resource supports all major browsers except for browsers below IE 9.
  3. Support for Promise API and URI Templates
    Promise is a feature of ES6. Promise means "prophet" in Chinese. Promise objects are used for asynchronous computation.
    URI Templates represent URI templates, somewhat similar to ASP.NET MVC's routing templates.
  4. Support for interceptors
    Interceptors are global, and the interceptor can do some processing before the request is sent and after the request is sent.
    Interceptors can be very useful in some scenarios, such as setting access_token in the headers before the request is sent, or providing a common processing method when the request fails.

vue-resource usage

1. Introduce vue-resource

<script src="js/vue.js"></script> <script src="js/vue-resource.js"></script>

2. After introducing vue-resource, you can use http based on the global Vue object, or you can use http based on a Vue instance.

// 基于全局Vue对象使用http
Vue.http.get('/someUrl', [options]).then(successCallback, errorCallback);
Vue.http.post('/someUrl', [body], [options]).then(successCallback, errorCallback);
 
// 在一个Vue实例内使用$http this.$http.get('/someUrl', [options]).then(successCallback, errorCallback); this.$http.post('/someUrl', [body], [options]).then(successCallback, errorCallback);

After sending the request, use the then method to process the response result. The then method has two parameters, the first parameter is the callback function when the response is successful, and the second parameter is the callback function when the response fails.
There are also two ways to write the callback function of the then method. The first is the traditional function writing method, and the second is the more concise ES 6 Lambda writing method:

// 传统写法
this.$http.get('/someUrl', [options]).then(function(response){ // 响应成功回调 }, function(response){ // 响应错误回调 }); // Lambda写法 this.$http.get('/someUrl', [options]).then((response) => { // 响应成功回调 }, (response) => { // 响应错误回调 });

Supported HTTP Methods

The request API of vue-resource is designed in REST style, it provides 7 kinds of request API:

get(url, [options])
head(url, [options])
delete(url, [options])
jsonp(url, [options])
post(url, [body], [options]) put(url, [body], [options]) patch(url, [body], [options])

In addition to jsonp, the other 6 API names are standard HTTP methods. When the server uses the REST API, the coding style of the client is almost the same as the coding style of the server, which can reduce the communication cost between front-end and back-end developers.

client request method Server-side processing method
this.$http.get(...) Getxxx
this.$http.post(...) Postxxx
this.$http.put(...) Putxxx
this.$http.delete(...) Deletexxx

options object

parameter Types of describe
url string the requested URL
method string The HTTP method of the request, e.g. 'GET', 'POST' or other HTTP methods
body Object, FormData string request body
params Object The requested URL parameter object
headers Object request header
timeout number Request timeout in milliseconds (0 means no timeout)
before function(request) The processing function before the request is sent, similar to jQuery's beforeSend function
progress function(event) ProgressEvent callback handler
credentials boolean Indicates whether credentials are required for cross-origin requests
emulateHTTP boolean Send PUT, PATCH, DELETE requests as HTTP POST, and set the X-HTTP-Method-Override of the request header
emulateJSON boolean Send the request body as application/x-www-form-urlencoded content type

The role of emulateHTTP

如果Web服务器无法处理PUT, PATCH和DELETE这种REST风格的请求,你可以启用enulateHTTP现象。启用该选项后,请求会以普通的POST方法发出,并且HTTP头信息的X-HTTP-Method-Override属性会设置为实际的HTTP方法。
Vue.http.options.emulateHTTP = true;

What emulateJSON does

如果Web服务器无法处理编码为application/json的请求,你可以启用emulateJSON选项。启用该选项后,请求会以application/x-www-form-urlencoded作为MIME type,就像普通的HTML表单一样。
Vue.http.options.emulateJSON = true;

response object

The response object contains the following properties:

method Types of describe
text() string Returns the response body as a string
json() Object Return the response body as a JSON object
blob() Blob Return the response body in binary form
Attributes Types of describe
ok boolean When the HTTP status code of the response is between 200 and 299, this property is true
status number The HTTP status code of the response
statusText string Status text of the response
headers Object response header

CURD instance

1. GET request

var demo = new Vue({
  el: '#app',
  data: {
    gridColumns: ['customerId', 'companyName', 'contactName', 'phone'],
    gridData: [],
    apiUrl: 'http://211.149.193.19:8080/api/customers'
  },
  ready: function() {
    this.getCustomers()
  },
  methods: {
    getCustomers: function() {
      this.$http.get(this.apiUrl) .then((response) => { this.$set('gridData', response.data) }) .catch(function(response) { console.log(response) }) } } })

The then method of this program only provides successCallback and omits errorCallback.
The catch method is used to catch program exceptions. The catch method is different from errorCallback. ErrorCallback is only called when the response fails, while catch is called during the entire request to response process, as long as the program fails.
In the callback function of the then method, you can also use this directly, this still points to the Vue instance:

getCustomers: function() {
  this.$http.get(this.apiUrl) .then((response) => { this.$set('gridData', response.data) }) .catch(function(response) { console.log(response) }) }

2. JSONP request

getCustomers: function() {
  this.$http.jsonp(this.apiUrl).then(function(response){ this.$set('gridData', response.data) }) }

3. POST request

var demo = new Vue({
  el: '#app',
  data: {
    show: false,
    gridColumns: [{
      name: 'customerId', isKey: true }, { name: 'companyName' }, { name: 'contactName' }, { name: 'phone' }], gridData: [], apiUrl: 'http://211.149.193.19:8080/api/customers', item: {} }, ready: function() { this.getCustomers() }, methods: { closeDialog: function() { this.show = false }, getCustomers: function() { var vm = this vm.$http.get(vm.apiUrl) .then((response) => { vm.$set('gridData', response.data) }) }, createCustomer: function() { var vm = this vm.$http.post(vm.apiUrl, vm.item) .then((response) => { vm.$set('item', {}) vm.getCustomers() }) this.show = false } } })

4. PUT request

updateCustomer: function() {
  var vm = this vm.$http.put(this.apiUrl + '/' + vm.item.customerId, vm.item) .then((response) => { vm.getCustomers() }) }

5. Delete request

deleteCustomer: function(customer){
  var vm = this
  vm.$http.delete(this.apiUrl + '/' + customer.customerId)
    .then((response) => { vm.getCustomers() }) }

vue-resource is a very lightweight plugin for handling HTTP requests. It provides two ways to handle HTTP requests:
1. Use Vue.http or this.http $2.
Use Vue.resource or $this.resource

data(){
    return{
      toplist:[],
      alllist:[]
    }
  },
  //vue-router
  route:{
    data({to}){
      //并发请求,利用 Promise 
      return Promise.all([ //简写 this.$http.get('http://192.168.30.235:9999/rest/knowledge/list',{'websiteId':2,'pageSize':5,'pageNo':1,'isTop':1}), //this.$http.get('http://192.168.30.235:9999/rest/knowledge/list',{'websiteId':2,'pageSize':20,'pageNo':1,'isTop':0}) //不简写 this.$http({ method:'GET', url:'http://192.168.30.235:9999/rest/knowledge/list', data:{'websiteId':2,'pageSize':20,'pageNo':1,'isTop':0}, headers: {"X-Requested-With": "XMLHttpRequest"}, emulateJSON: true }) ]).then(function(data){//es5写法 return{ toplist:data[0].data.knowledgeList, alllist:data[1].data.knowledgeList } //es6写法 .then()部分 //.then(([toplist,alllist])=>({toplist,alllist})) },function(error){ //error }) } }

vue axios

After vue2.0, vue-resource is no longer updated, but axios is recommended. Promise-based HTTP request client that works in both the browser and Node.js.

  • Features
    1. Send XMLHttpRequests
    in the browser2. Send http requests in node.js3
    . Support Promise API4
    . Intercept requests and responses5
    . Convert request and response
    data6. Cancel requests7
    . Automatically convert JSON
    data8 , client-side support to protect security from CSRF/XSRF attacks
  • Install axios
    $ npm install axios

  • Introduce axios import axios from 'axios' in the file to be used
  • GET request
// 向具有指定ID的用户发出请求
axios.get('/user?ID=12345')
.then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); }); // 也可以通过 params 对象传递参数 axios.get('/user', { params: { ID: 12345 } }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); });
  • POST request
axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); });
  • Execute multiple concurrent requests
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) { //两个请求现已完成 }));
  • axios API: Requests can be made by passing the relevant configuration to axios.
axios(config)
// 发送一个 POST 请求
axios({
method: 'post',
url: '/user/12345', data: { firstName: 'Fred', lastName: 'Flintstone' } });
axios(url[, config])
// 发送一个 GET 请求 (GET请求是默认请求模式)
axios('/user/12345');

Request method alias:

为了方便起见,已经为所有支持的请求方法提供了别名。
axios.request(config)
axios.get(url [,config]) axios.delete(url [,config]) axios.head(url [,config]) axios.post(url [,data [,config]]) axios.put(url [,data [,config]]) axios.patch(url [,data [,config]]) 注意:当使用别名方法时,不需要在config中指定url,method和data属性。
  • Concurrency
    helper functions handle concurrent requests.
    axios.all(iterable)
    axios.spread(callback)
  • Creating an instance
    can also create a new instance of axios with a custom configuration.
    axios.create([config])
var instance = axios.create({
baseURL: 'https://some-domain.com/api/',
timeout: 1000,
headers: {'X-Custom-Header': 'foobar'} });
  • Instance Methods
    Available instance methods are listed below. The specified configuration will be merged with the instance configuration.
axios#request(config)
axios#get(url [,config])
axios#delete(url [,config])
axios#head(url [,config])
axios#post(url [,data [,config]]) axios#put(url [,data [,config]]) axios#patch(url [,data [,config]])
  • Request Configuration
    These are the available configuration options for making requests. Only the url is required. If no method is specified, the request will default to GET.
{
// `url`是将用于请求的服务器URL
url: '/user',
 
// `method`是发出请求时使用的请求方法
method: 'get', // 默认 // `baseURL`将被添加到`url`前面,除非`url`是绝对的。 // 可以方便地为 axios 的实例设置`baseURL`,以便将相对 URL 传递给该实例的方法。 baseURL: 'https://some-domain.com/api/', // `transformRequest`允许在请求数据发送到服务器之前对其进行更改 // 这只适用于请求方法'PUT','POST'和'PATCH' // 数组中的最后一个函数必须返回一个字符串,一个 ArrayBuffer或一个 Stream  transformRequest: [function (data) { // 做任何你想要的数据转换 return data; }], // `transformResponse`允许在 then / catch之前对响应数据进行更改 transformResponse: [function (data) { // Do whatever you want to transform the data return data; }], // `headers`是要发送的自定义 headers headers: {'X-Requested-With': 'XMLHttpRequest'}, // `params`是要与请求一起发送的URL参数 // 必须是纯对象或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 // - Browser only: FormData, File, Blob // - Node only: Stream data: { firstName: 'Fred' }, // `timeout`指定请求超时之前的毫秒数。 // 如果请求的时间超过'timeout',请求将被中止。 timeout: 1000, // `withCredentials`指示是否跨站点访问控制请求 // should be made using credentials withCredentials: false, // default // `adapter'允许自定义处理请求,这使得测试更容易。 // 返回一个promise并提供一个有效的响应(参见[response docs](#response-api)) adapter: function (config) { /* ... */ }, // `auth'表示应该使用 HTTP 基本认证,并提供凭据。 // 这将设置一个`Authorization'头,覆盖任何现有的`Authorization'自定义头,使用`headers`设置。 auth: { username: 'janedoe', password: 's00pers3cret' }, // “responseType”表示服务器将响应的数据类型 // 包括 'arraybuffer', 'blob', 'document', 'json', 'text', 'stream' responseType: 'json', // default //`xsrfCookieName`是要用作 xsrf 令牌的值的cookie的名称 xsrfCookieName: 'XSRF-TOKEN', // default // `xsrfHeaderName`是携带xsrf令牌值的http头的名称 xsrfHeaderName: 'X-XSRF-TOKEN', // default // `onUploadProgress`允许处理上传的进度事件 onUploadProgress: function (progressEvent) { // 使用本地 progress 事件做任何你想要做的 }, // `onDownloadProgress`允许处理下载的进度事件 onDownloadProgress: function (progressEvent) { // Do whatever you want with the native progress event }, // `maxContentLength`定义允许的http响应内容的最大大小 maxContentLength: 2000, // `validateStatus`定义是否解析或拒绝给定的promise // HTTP响应状态码。如果`validateStatus`返回`true`(或被设置为`null` promise将被解析;否则,promise将被 // 拒绝。 validateStatus: function (status) { return status >= 200 && status < 300; // default }, // `maxRedirects`定义在node.js中要遵循的重定向的最大数量。 // 如果设置为0,则不会遵循重定向。 maxRedirects: 5, // 默认 // `httpAgent`和`httpsAgent`用于定义在node.js中分别执行http和https请求时使用的自定义代理。 // 允许配置类似`keepAlive`的选项, // 默认情况下不启用。 httpAgent: new http.Agent({ keepAlive: true }), httpsAgent: new https.Agent({ keepAlive: true }), // 'proxy'定义代理服务器的主机名和端口 // `auth`表示HTTP Basic auth应该用于连接到代理,并提供credentials。 // 这将设置一个`Proxy-Authorization` header,覆盖任何使用`headers`设置的现有的`Proxy-Authorization` 自定义 headers。 proxy: { host: '127.0.0.1', port: 9000, auth: : { username: 'mikeymike', password: 'rapunz3l' } }, // “cancelToken”指定可用于取消请求的取消令牌 // (see Cancellation section below for details) cancelToken: new CancelToken(function (cancel) { }) }

When using then, you will receive a response like this:

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); });
  • Configure defaults

1. Global axios default value

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. Custom instance default value

//在创建实例时设置配置默认值
var instance = axios.create({
   baseURL:'https://api.example.com'
});
//在实例创建后改变默认值 instance.defaults.headers.common ['Authorization'] = AUTH_TOKEN;

3. Configuration priority order
The configuration will be merged with the priority order. The order is the library defaults in lib/defaults.js, then the defaults property of the instance, and finally the request's config parameter. The latter will take precedence over the former. Here is an example.

//使用库提供的配置默认值创建实例
//此时,超时配置值为`0`,这是库的默认值
var instance = axios.create();
 
//覆盖库的超时默认值
//现在所有请求将在超时前等待2.5秒 instance.defaults.timeout = 2500; //覆盖此请求的超时,因为它知道需要很长时间 instance.get('/ longRequest',{ timeout:5000 });
  • Interceptors
    you can intercept requests or responses before they are processed by then or catch
//添加请求拦截器
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); });

If you may need to remove the interceptor later.

var myInterceptor = axios.interceptors.request.use(function () {/*...*/}); axios.interceptors.request.eject(myInterceptor);

You can add interceptors to custom instances of axios.

var instance = axios.create();
instance.interceptors.request.use(function () {/*...*/});
  • handle errors
axios.get('/ user / 12345')
   .catch(function(error){
     if(error.response){ //请求已发出,但服务器使用状态代码进行响应 //落在2xx的范围之外 console.log(error.response.data); console.log(error.response.status); console.log(error.response.headers); } else { //在设置触发错误的请求时发生了错误 console.log('Error',error.message); }} console.log(error.config); });

You can define custom HTTP status code error ranges using the validateStatus configuration option.

axios.get('/ user / 12345',{
   validateStatus:function(status){
     return status < 500; //仅当状态代码大于或等于500时拒绝 }} })
  • You can cancel
    the request with the cancellation token.

    The axios cancel token API is based on a cancelable promise and is currently in phase 1.
    You can use the CancelToken.source factory to create a cancellation token like this:

var CancelToken = axios.CancelToken;
var source = CancelToken.source();
 
axios.get('/user/12345', {
cancelToken: source.token
}).catch(function(thrown) { if (axios.isCancel(thrown)) { console.log('Request canceled', thrown.message); } else { // 处理错误 } }); //取消请求(消息参数是可选的) source.cancel('操作被用户取消。'); 

You can also create a cancellation token by passing an executor function to the CancelToken constructor:

var CancelToken = axios.CancelToken;
var cancel;
 
axios.get('/ user / 12345',{
   cancelToken:new CancelToken(function executor(c){ //一个执行器函数接收一个取消函数作为参数 cancel = c; }) }); // 取消请求 clear();

Note: You can cancel several requests with the same cancellation token.

  • Use application/x-www-form-urlencoded format

By default, axios serializes JavaScript objects to JSON. To send data in application/x-www-form-urlencoded format, you can use one of the following options.

1. Browser
In the browser, you can use the URLSearchParams API as follows:

var params = new URLSearchParams();
params.append('param1', 'value1'); params.append('param2', 'value2'); axios.post('/foo', params); 请注意,所有浏览器都不支持URLSearchParams,但是有一个polyfill可用(确保polyfill全局环境)。

Alternatively, you can use the qs library to encode the data:

var qs = require('qs');
axios.post('/foo', qs.stringify({ 'bar': 123 });

2. Node.js
In node.js, you can use the querystring module as follows:

var querystring = require('querystring');
axios.post('http://something.com/', querystring.stringify({ foo: 'bar' });

3. TypeScript
axios includes TypeScript definitions.

import axios from 'axios';
axios.get('/user?ID=12345');

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324780096&siteId=291194637