or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

tessl/npm-vue-resource

The HTTP client for Vue.js providing services for making web requests and handling responses using XMLHttpRequest or JSONP

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/vue-resource@1.5.x

To install, run

npx @tessl/cli install tessl/npm-vue-resource@1.5.0

0

# Vue Resource

1

2

Vue 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.

3

4

## Package Information

5

6

- **Package Name**: vue-resource

7

- **Package Type**: npm

8

- **Language**: JavaScript/TypeScript

9

- **Installation**: `npm install vue-resource`

10

11

## Core Imports

12

13

```javascript

14

import VueResource from "vue-resource";

15

Vue.use(VueResource);

16

```

17

18

For CommonJS:

19

20

```javascript

21

const VueResource = require("vue-resource");

22

Vue.use(VueResource);

23

```

24

25

Browser (CDN):

26

27

```html

28

<script src="https://cdn.jsdelivr.net/npm/vue-resource@1.5.3"></script>

29

```

30

31

## Basic Usage

32

33

```javascript

34

// Install the plugin

35

Vue.use(VueResource);

36

37

// In a Vue component

38

export default {

39

methods: {

40

fetchData() {

41

// GET request

42

this.$http.get('/api/users').then(response => {

43

this.users = response.body;

44

}, response => {

45

console.error('Error:', response);

46

});

47

48

// POST request

49

this.$http.post('/api/users', {name: 'John', email: 'john@example.com'})

50

.then(response => {

51

console.log('User created:', response.body);

52

});

53

54

// Using Resources for RESTful operations

55

const UserResource = this.$resource('/api/users{/id}');

56

UserResource.get({id: 1}).then(response => {

57

console.log('User:', response.body);

58

});

59

60

// Using Vue context-aware Promises

61

this.$promise((resolve, reject) => {

62

setTimeout(() => resolve('Delayed result'), 1000);

63

}).then(function(result) {

64

// 'this' is automatically bound to the Vue component

65

this.delayedData = result;

66

});

67

}

68

}

69

}

70

```

71

72

## Architecture

73

74

Vue Resource is built around several key components:

75

76

- **Plugin System**: Installs as a Vue plugin, extending Vue instances with HTTP capabilities

77

- **HTTP Service**: Core HTTP client with method shortcuts and interceptor support

78

- **Resource Service**: RESTful resource abstraction with predefined CRUD operations

79

- **URL Service**: URI templating and transformation utilities

80

- **Promise Service**: Vue context-aware Promise wrapper for proper binding

81

- **Interceptor Chain**: Request/response transformation pipeline

82

- **Multi-Client Support**: Automatic client selection (XHR, JSONP, Node.js, XDomainRequest)

83

84

## Capabilities

85

86

### HTTP Client

87

88

Core HTTP client functionality for making web requests with support for all standard HTTP methods, custom headers, and interceptors.

89

90

```javascript { .api }

91

// Main HTTP function

92

function $http(options: HttpOptions): Promise<HttpResponse>;

93

94

// HTTP method shortcuts

95

function $http.get(url: string, options?: HttpOptions): Promise<HttpResponse>;

96

function $http.post(url: string, body?: any, options?: HttpOptions): Promise<HttpResponse>;

97

function $http.put(url: string, body?: any, options?: HttpOptions): Promise<HttpResponse>;

98

function $http.patch(url: string, body?: any, options?: HttpOptions): Promise<HttpResponse>;

99

function $http.delete(url: string, options?: HttpOptions): Promise<HttpResponse>;

100

function $http.head(url: string, options?: HttpOptions): Promise<HttpResponse>;

101

function $http.jsonp(url: string, options?: HttpOptions): Promise<HttpResponse>;

102

103

interface HttpOptions {

104

url?: string;

105

method?: string;

106

body?: any;

107

params?: any;

108

headers?: any;

109

before?(request: any): any;

110

progress?(event: any): any;

111

credentials?: boolean;

112

emulateHTTP?: boolean;

113

emulateJSON?: boolean;

114

}

115

116

interface HttpResponse {

117

data: any;

118

body: any;

119

ok: boolean;

120

status: number;

121

statusText: string;

122

url: string;

123

headers: Headers;

124

text(): Promise<string>;

125

json(): Promise<any>;

126

blob(): Promise<Blob>;

127

}

128

```

129

130

[HTTP Client](./http-client.md)

131

132

### RESTful Resources

133

134

Resource abstraction for RESTful APIs providing predefined CRUD operations with URL templating and parameter binding.

135

136

```javascript { .api }

137

function $resource(

138

url: string,

139

params?: object,

140

actions?: object,

141

options?: HttpOptions

142

): ResourceMethods;

143

144

interface ResourceMethods {

145

get: ResourceMethod;

146

save: ResourceMethod;

147

query: ResourceMethod;

148

update: ResourceMethod;

149

remove: ResourceMethod;

150

delete: ResourceMethod;

151

}

152

153

interface ResourceMethod {

154

(params?: any, data?: any): Promise<HttpResponse>;

155

(params?: any): Promise<HttpResponse>;

156

(): Promise<HttpResponse>;

157

}

158

```

159

160

[RESTful Resources](./resources.md)

161

162

### URL Processing

163

164

URL templating and transformation utilities for building dynamic URLs with parameter substitution and query string handling.

165

166

```javascript { .api }

167

function $url(url: string, params?: object): string;

168

169

// Static methods

170

function $url.params(obj: object): string;

171

function $url.parse(url: string): UrlComponents;

172

173

interface UrlComponents {

174

href: string;

175

protocol: string;

176

port: string;

177

host: string;

178

hostname: string;

179

pathname: string;

180

search: string;

181

hash: string;

182

}

183

```

184

185

[URL Processing](./url-processing.md)

186

187

### Interceptors

188

189

Request and response transformation pipeline for modifying HTTP requests before they are sent and responses before they are processed.

190

191

```javascript { .api }

192

interface HttpInterceptor {

193

request?(request: HttpOptions): HttpOptions;

194

response?(response: HttpResponse): HttpResponse;

195

}

196

197

// Built-in interceptors

198

const interceptors = {

199

before: HttpInterceptor;

200

method: HttpInterceptor;

201

jsonp: HttpInterceptor;

202

json: HttpInterceptor;

203

form: HttpInterceptor;

204

header: HttpInterceptor;

205

cors: HttpInterceptor;

206

}

207

```

208

209

[Interceptors](./interceptors.md)

210

211

### Promise Service

212

213

Vue context-aware Promise wrapper that automatically binds callback functions to the appropriate Vue component context, ensuring proper `this` binding in async operations.

214

215

```javascript { .api }

216

function $promise(executor: (resolve: Function, reject: Function) => void): PromiseObj;

217

218

// Static Promise methods

219

function Promise.all(iterable: any[], context?: any): PromiseObj;

220

function Promise.resolve(value: any, context?: any): PromiseObj;

221

function Promise.reject(reason: any, context?: any): PromiseObj;

222

function Promise.race(iterable: any[], context?: any): PromiseObj;

223

224

interface PromiseObj {

225

bind(context: any): PromiseObj;

226

then(fulfilled?: Function, rejected?: Function): PromiseObj;

227

catch(rejected: Function): PromiseObj;

228

finally(callback: Function): PromiseObj;

229

}

230

```

231

232

[Promise Service](./promise-service.md)

233

234

## Global Configuration

235

236

Vue Resource can be configured globally through static properties:

237

238

```javascript { .api }

239

// HTTP configuration

240

Vue.http.options: HttpOptions & { root: string };

241

Vue.http.headers: HttpHeaders;

242

Vue.http.interceptors: (HttpInterceptor | string)[];

243

Vue.http.interceptor: { [name: string]: HttpInterceptor };

244

245

// URL configuration

246

Vue.url.options: {

247

url: string;

248

root: string | null;

249

params: object;

250

};

251

Vue.url.transform: {

252

template: Function;

253

query: Function;

254

root: Function;

255

};

256

Vue.url.transforms: string[]; // ['template', 'query', 'root']

257

258

// Resource configuration

259

Vue.resource.actions: ResourceActions;

260

261

// Promise static methods

262

Vue.Promise.all: (iterable: any[], context?: any) => PromiseObj;

263

Vue.Promise.resolve: (value: any, context?: any) => PromiseObj;

264

Vue.Promise.reject: (reason: any, context?: any) => PromiseObj;

265

Vue.Promise.race: (iterable: any[], context?: any) => PromiseObj;

266

267

// Default header structure

268

interface HttpHeaders {

269

put: { 'Content-Type': 'application/json;charset=utf-8' };

270

post: { 'Content-Type': 'application/json;charset=utf-8' };

271

patch: { 'Content-Type': 'application/json;charset=utf-8' };

272

delete: { 'Content-Type': 'application/json;charset=utf-8' };

273

common: { 'Accept': 'application/json, text/plain, */*' };

274

custom: { [key: string]: string };

275

}

276

```

277

278

**Usage Examples:**

279

280

```javascript

281

// HTTP configuration

282

Vue.http.options.root = '/api';

283

Vue.http.options.credentials = true;

284

Vue.http.options.timeout = 10000;

285

286

// Default headers

287

Vue.http.headers.common['Authorization'] = 'Bearer token';

288

Vue.http.headers.post['Content-Type'] = 'application/json';

289

Vue.http.headers.custom['X-API-Key'] = 'your-api-key';

290

291

// URL configuration

292

Vue.url.options.root = 'https://api.example.com';

293

294

// Interceptors

295

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

296

// modify request

297

console.log('Sending request to:', request.url);

298

next(function(response) {

299

// modify response

300

console.log('Received response:', response.status);

301

});

302

});

303

304

// Add custom interceptor by name

305

Vue.http.interceptor.myCustom = function(request, next) {

306

request.headers.set('X-Custom-Header', 'value');

307

next();

308

};

309

Vue.http.interceptors.push('myCustom');

310

```

311

312

## Types

313

314

```typescript { .api }

315

interface HttpHeaders {

316

put?: { [key: string]: string };

317

post?: { [key: string]: string };

318

patch?: { [key: string]: string };

319

delete?: { [key: string]: string };

320

common?: { [key: string]: string };

321

custom?: { [key: string]: string };

322

[key: string]: any;

323

}

324

325

interface ResourceActions {

326

get: { method: string };

327

save: { method: string };

328

query: { method: string };

329

update: { method: string };

330

remove: { method: string };

331

delete: { method: string };

332

}

333

334

interface Headers {

335

/** Internal header storage map */

336

map: { [normalizedName: string]: string[] };

337

/** Check if header exists (case-insensitive) */

338

has(name: string): boolean;

339

/** Get header value (comma-separated if multiple values) */

340

get(name: string): string | null;

341

/** Get all values for a header as array */

342

getAll(name: string): string[];

343

/** Set header value (replaces existing values) */

344

set(name: string, value: string): void;

345

/** Add header value (appends to existing values) */

346

append(name: string, value: string): void;

347

/** Delete header (case-insensitive) */

348

delete(name: string): void;

349

/** Delete all headers */

350

deleteAll(): void;

351

/** Iterate over all header values */

352

forEach(callback: (value: string, name: string, headers: Headers) => void, thisArg?: any): void;

353

}

354

355

interface PromiseObj {

356

/** Underlying native Promise instance */

357

promise: Promise<any>;

358

/** Vue component context for callback binding */

359

context: any;

360

/** Bind callbacks to specified context */

361

bind(context: any): PromiseObj;

362

/** Add success/error handlers with context binding */

363

then(fulfilled?: Function, rejected?: Function): PromiseObj;

364

/** Add error handler with context binding */

365

catch(rejected: Function): PromiseObj;

366

/** Add cleanup handler that runs regardless of outcome */

367

finally(callback: Function): PromiseObj;

368

}

369

370

interface PromiseConstructor {

371

/** Create context-aware promise from all promises in iterable */

372

all(iterable: any[], context?: any): PromiseObj;

373

/** Create context-aware promise that resolves with value */

374

resolve(value: any, context?: any): PromiseObj;

375

/** Create context-aware promise that rejects with reason */

376

reject(reason: any, context?: any): PromiseObj;

377

/** Create context-aware promise that races promises in iterable */

378

race(iterable: any[], context?: any): PromiseObj;

379

}

380

```