HTTP

March 2, 2018 ยท View on GitHub

The http service can be used globally Vue.http or in a Vue instance this.$http.

Usage

A Vue instance provides the this.$http service which can send HTTP requests. A request method call returns a Promise that resolves to the response. Also the Vue instance will be automatically bound to this in all function callbacks.

{
  // GET /someUrl
  this.$http.get('/someUrl').then(response => {
    // success callback
  }, response => {
    // error callback
  });
}

Methods

Shortcut methods are available for all request types. These methods work globally or in a Vue instance.

// global Vue object
Vue.http.get('/someUrl', [config]).then(successCallback, errorCallback);
Vue.http.post('/someUrl', [body], [config]).then(successCallback, errorCallback);

// in a Vue instance
this.$http.get('/someUrl', [config]).then(successCallback, errorCallback);
this.$http.post('/someUrl', [body], [config]).then(successCallback, errorCallback);

List of shortcut methods:

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

Config

ParameterTypeDescription
urlstringURL to which the request is sent
bodyObject, FormData, stringData to be sent as the request body
headersObjectHeaders object to be sent as HTTP request headers
paramsObjectParameters object to be sent as URL parameters
methodstringHTTP method (e.g. GET, POST, ...)
responseTypestringType of the response body (e.g. text, blob, json, ...)
timeoutnumberRequest timeout in milliseconds (0 means no timeout)
credentialsbooleanIndicates whether or not cross-site Access-Control requests should be made using credentials
emulateHTTPbooleanSend PUT, PATCH and DELETE requests with a HTTP POST and set the X-HTTP-Method-Override header
emulateJSONbooleanSend request body as application/x-www-form-urlencoded content type
beforefunction(request)Callback function to modify the request object before it is sent
uploadProgressfunction(event)Callback function to handle the ProgressEvent of uploads
downloadProgressfunction(event)Callback function to handle the ProgressEvent of downloads

Response

A request resolves to a response object with the following properties and methods:

PropertyTypeDescription
urlstringResponse URL origin
bodyObject, Blob, stringResponse body
headersHeaderResponse Headers object
okbooleanHTTP status code between 200 and 299
statusnumberHTTP status code of the response
statusTextstringHTTP status text of the response
MethodTypeDescription
text()PromiseResolves the body as string
json()PromiseResolves the body as parsed JSON object
blob()PromiseResolves the body as Blob object

Example

{
  // POST /someUrl
  this.$http.post('/someUrl', {foo: 'bar'}).then(response => {

    // get status
    response.status;

    // get status text
    response.statusText;

    // get 'Expires' header
    response.headers.get('Expires');

    // get body data
    this.someData = response.body;

  }, response => {
    // error callback
  });
}

Send a get request with URL query parameters and a custom headers.

{
  // GET /someUrl?foo=bar
  this.$http.get('/someUrl', {params: {foo: 'bar'}, headers: {'X-Custom': '...'}}).then(response => {
    // success callback
  }, response => {
    // error callback
  });
}

Fetch an image and use the blob() method to extract the image body content from the response.

{
  // GET /image.jpg
  this.$http.get('/image.jpg', {responseType: 'blob'}).then(response => {

    // resolve to Blob
    return response.blob();

  }).then(blob => {
    // use image Blob
  });
}

Interceptors

Interceptors can be defined globally and are used for pre- and postprocessing of a request. If a request is sent using this.$http or this.$resource the current Vue instance is available as this in a interceptor callback.

Request processing

Vue.http.interceptors.push(function(request) {

  // modify method
  request.method = 'POST';

  // modify headers
  request.headers.set('X-CSRF-TOKEN', 'TOKEN');
  request.headers.set('Authorization', 'Bearer TOKEN');

});

Request and Response processing

Vue.http.interceptors.push(function(request) {

  // modify request
  request.method = 'POST';

  // return response callback
  return function(response) {

    // modify response
    response.body = '...';

  };
});

Return a Response and stop processing

Vue.http.interceptors.push(function(request) {

  // modify request ...

  // stop and return response
  return request.respondWith(body, {
    status: 404,
    statusText: 'Not found'
  });
});

Overriding default interceptors

All default interceptors callbacks can be overriden to change their behavior. All interceptors are exposed through the Vue.http.interceptor object with their names before, method, jsonp, json, form, header and cors.

Vue.http.interceptor.before = function(request) {

  // override before interceptor

};