The HTTP client for Vue.js providing services for making web requests and handling responses using XMLHttpRequest or JSONP
npx @tessl/cli install tessl/npm-vue-resource@1.5.0Vue Resource is the HTTP client for Vue.js providing services for making web requests and handling responses using XMLHttpRequest or JSONP. It integrates seamlessly with Vue.js as a plugin, adding $http and $resource services to all Vue instances with support for interceptors, URI templates, and Promise-based operations.
npm install vue-resourceimport VueResource from "vue-resource";
Vue.use(VueResource);For CommonJS:
const VueResource = require("vue-resource");
Vue.use(VueResource);Browser (CDN):
<script src="https://cdn.jsdelivr.net/npm/vue-resource@1.5.3"></script>// Install the plugin
Vue.use(VueResource);
// In a Vue component
export default {
methods: {
fetchData() {
// GET request
this.$http.get('/api/users').then(response => {
this.users = response.body;
}, response => {
console.error('Error:', response);
});
// POST request
this.$http.post('/api/users', {name: 'John', email: 'john@example.com'})
.then(response => {
console.log('User created:', response.body);
});
// Using Resources for RESTful operations
const UserResource = this.$resource('/api/users{/id}');
UserResource.get({id: 1}).then(response => {
console.log('User:', response.body);
});
// Using Vue context-aware Promises
this.$promise((resolve, reject) => {
setTimeout(() => resolve('Delayed result'), 1000);
}).then(function(result) {
// 'this' is automatically bound to the Vue component
this.delayedData = result;
});
}
}
}Vue Resource is built around several key components:
Core HTTP client functionality for making web requests with support for all standard HTTP methods, custom headers, and interceptors.
// Main HTTP function
function $http(options: HttpOptions): Promise<HttpResponse>;
// HTTP method shortcuts
function $http.get(url: string, options?: HttpOptions): Promise<HttpResponse>;
function $http.post(url: string, body?: any, options?: HttpOptions): Promise<HttpResponse>;
function $http.put(url: string, body?: any, options?: HttpOptions): Promise<HttpResponse>;
function $http.patch(url: string, body?: any, options?: HttpOptions): Promise<HttpResponse>;
function $http.delete(url: string, options?: HttpOptions): Promise<HttpResponse>;
function $http.head(url: string, options?: HttpOptions): Promise<HttpResponse>;
function $http.jsonp(url: string, options?: HttpOptions): Promise<HttpResponse>;
interface HttpOptions {
url?: string;
method?: string;
body?: any;
params?: any;
headers?: any;
before?(request: any): any;
progress?(event: any): any;
credentials?: boolean;
emulateHTTP?: boolean;
emulateJSON?: boolean;
}
interface HttpResponse {
data: any;
body: any;
ok: boolean;
status: number;
statusText: string;
url: string;
headers: Headers;
text(): Promise<string>;
json(): Promise<any>;
blob(): Promise<Blob>;
}Resource abstraction for RESTful APIs providing predefined CRUD operations with URL templating and parameter binding.
function $resource(
url: string,
params?: object,
actions?: object,
options?: HttpOptions
): ResourceMethods;
interface ResourceMethods {
get: ResourceMethod;
save: ResourceMethod;
query: ResourceMethod;
update: ResourceMethod;
remove: ResourceMethod;
delete: ResourceMethod;
}
interface ResourceMethod {
(params?: any, data?: any): Promise<HttpResponse>;
(params?: any): Promise<HttpResponse>;
(): Promise<HttpResponse>;
}URL templating and transformation utilities for building dynamic URLs with parameter substitution and query string handling.
function $url(url: string, params?: object): string;
// Static methods
function $url.params(obj: object): string;
function $url.parse(url: string): UrlComponents;
interface UrlComponents {
href: string;
protocol: string;
port: string;
host: string;
hostname: string;
pathname: string;
search: string;
hash: string;
}Request and response transformation pipeline for modifying HTTP requests before they are sent and responses before they are processed.
interface HttpInterceptor {
request?(request: HttpOptions): HttpOptions;
response?(response: HttpResponse): HttpResponse;
}
// Built-in interceptors
const interceptors = {
before: HttpInterceptor;
method: HttpInterceptor;
jsonp: HttpInterceptor;
json: HttpInterceptor;
form: HttpInterceptor;
header: HttpInterceptor;
cors: HttpInterceptor;
}Vue context-aware Promise wrapper that automatically binds callback functions to the appropriate Vue component context, ensuring proper this binding in async operations.
function $promise(executor: (resolve: Function, reject: Function) => void): PromiseObj;
// Static Promise methods
function Promise.all(iterable: any[], context?: any): PromiseObj;
function Promise.resolve(value: any, context?: any): PromiseObj;
function Promise.reject(reason: any, context?: any): PromiseObj;
function Promise.race(iterable: any[], context?: any): PromiseObj;
interface PromiseObj {
bind(context: any): PromiseObj;
then(fulfilled?: Function, rejected?: Function): PromiseObj;
catch(rejected: Function): PromiseObj;
finally(callback: Function): PromiseObj;
}Vue Resource can be configured globally through static properties:
// HTTP configuration
Vue.http.options: HttpOptions & { root: string };
Vue.http.headers: HttpHeaders;
Vue.http.interceptors: (HttpInterceptor | string)[];
Vue.http.interceptor: { [name: string]: HttpInterceptor };
// URL configuration
Vue.url.options: {
url: string;
root: string | null;
params: object;
};
Vue.url.transform: {
template: Function;
query: Function;
root: Function;
};
Vue.url.transforms: string[]; // ['template', 'query', 'root']
// Resource configuration
Vue.resource.actions: ResourceActions;
// Promise static methods
Vue.Promise.all: (iterable: any[], context?: any) => PromiseObj;
Vue.Promise.resolve: (value: any, context?: any) => PromiseObj;
Vue.Promise.reject: (reason: any, context?: any) => PromiseObj;
Vue.Promise.race: (iterable: any[], context?: any) => PromiseObj;
// Default header structure
interface HttpHeaders {
put: { 'Content-Type': 'application/json;charset=utf-8' };
post: { 'Content-Type': 'application/json;charset=utf-8' };
patch: { 'Content-Type': 'application/json;charset=utf-8' };
delete: { 'Content-Type': 'application/json;charset=utf-8' };
common: { 'Accept': 'application/json, text/plain, */*' };
custom: { [key: string]: string };
}Usage Examples:
// HTTP configuration
Vue.http.options.root = '/api';
Vue.http.options.credentials = true;
Vue.http.options.timeout = 10000;
// Default headers
Vue.http.headers.common['Authorization'] = 'Bearer token';
Vue.http.headers.post['Content-Type'] = 'application/json';
Vue.http.headers.custom['X-API-Key'] = 'your-api-key';
// URL configuration
Vue.url.options.root = 'https://api.example.com';
// Interceptors
Vue.http.interceptors.push(function(request, next) {
// modify request
console.log('Sending request to:', request.url);
next(function(response) {
// modify response
console.log('Received response:', response.status);
});
});
// Add custom interceptor by name
Vue.http.interceptor.myCustom = function(request, next) {
request.headers.set('X-Custom-Header', 'value');
next();
};
Vue.http.interceptors.push('myCustom');interface HttpHeaders {
put?: { [key: string]: string };
post?: { [key: string]: string };
patch?: { [key: string]: string };
delete?: { [key: string]: string };
common?: { [key: string]: string };
custom?: { [key: string]: string };
[key: string]: any;
}
interface ResourceActions {
get: { method: string };
save: { method: string };
query: { method: string };
update: { method: string };
remove: { method: string };
delete: { method: string };
}
interface Headers {
/** Internal header storage map */
map: { [normalizedName: string]: string[] };
/** Check if header exists (case-insensitive) */
has(name: string): boolean;
/** Get header value (comma-separated if multiple values) */
get(name: string): string | null;
/** Get all values for a header as array */
getAll(name: string): string[];
/** Set header value (replaces existing values) */
set(name: string, value: string): void;
/** Add header value (appends to existing values) */
append(name: string, value: string): void;
/** Delete header (case-insensitive) */
delete(name: string): void;
/** Delete all headers */
deleteAll(): void;
/** Iterate over all header values */
forEach(callback: (value: string, name: string, headers: Headers) => void, thisArg?: any): void;
}
interface PromiseObj {
/** Underlying native Promise instance */
promise: Promise<any>;
/** Vue component context for callback binding */
context: any;
/** Bind callbacks to specified context */
bind(context: any): PromiseObj;
/** Add success/error handlers with context binding */
then(fulfilled?: Function, rejected?: Function): PromiseObj;
/** Add error handler with context binding */
catch(rejected: Function): PromiseObj;
/** Add cleanup handler that runs regardless of outcome */
finally(callback: Function): PromiseObj;
}
interface PromiseConstructor {
/** Create context-aware promise from all promises in iterable */
all(iterable: any[], context?: any): PromiseObj;
/** Create context-aware promise that resolves with value */
resolve(value: any, context?: any): PromiseObj;
/** Create context-aware promise that rejects with reason */
reject(reason: any, context?: any): PromiseObj;
/** Create context-aware promise that races promises in iterable */
race(iterable: any[], context?: any): PromiseObj;
}