Skip to content

Latest commit

 

History

History
78 lines (55 loc) · 3.57 KB

README.md

File metadata and controls

78 lines (55 loc) · 3.57 KB

Http

A Vue plugin that setups the vue-resource module and exposes some http utilities methods.

Dependencies

Usage

  1. Import the plugin and register it:
import httpPlugin from "@/../ditto/http";
Vue.use(httpPlugin);
  1. Use the exposed methods as you wish (the methods are available at Vue.$http (or this.$http if you have access to a component scope)):
Vue.$http
  .get("test")
  .then(response => console.log(response))
  .catch(error => console.error(error));

Options

Available plugin options:

Option Description Default
httpRoot the base url of all the http requests, (see the docs for more information) /
addTrailingSlashInterceptor whether to add an interceptor that adds a trailing slash / to all http request urls, should be used only until the django/vue router bug is resolved @simone false
Vue.use(httpPlugin, {
  httpRoot: "/api",
  addTrailingSlashInterceptor: true
});

Extensions

Extensions consists in custom plugins that you want to install after http plugin setup ends. The plugin extensions can access to the http plugin functionalities and can have their options object.

import customPlugin from "...";
const customPluginOptions = {...};

Vue.use(httpPlugin, {
  extensions: [
    {
      plugin: customPlugin,
      options: customPluginOptions
    }
  ]
});

Methods

The plugin exposes the following methods, available at Vue.$http (or this.$http if you have access to a component scope):

  • addHeader(key, value) adds a new (key, value) pair to the http headers of all the http requests
  • setRoot(url) updates the base url of all the http requests (see options)
  • getUrl(endpoint, params, useRandomString = true) given an object of params returns the string composed adding to the endpoint string the required request parameters; when useRandomString is true, a random parameter is added to the resulting string (the random parameter is used to prevent request result caching in IE); example: getUrl("test", {a: 1, b: 2}) => test?a=1&b=2&r=asdfasd

All these methods return a Promise:

  • get(endpoint, params) computes the request url using the getUrl function and resolves the promise when the http get request receives a response, returning that response as a json object
  • patch(endpoint, params, data) computes the request url using the getUrl function and resolves the promise when the http patch request receives a response; data is the body of the http request
  • post(endpoint, params, data) computes the request url using the getUrl function and resolves the promise when the http post request receives a response; data is the body of the http request
  • remove(endpoint, params) computes the request url using the getUrl function and resolves the promise when the http delete request receives a response

Example code

See the http examples code for more information.