ajax promise 类库,pajax - Promise based AJAX library

pajax

7b78ca15ab7024281c31197738280d25.png

pajax is a library for promise based XHR request.

It has similarities to the upcoming Fetch standard.

Installation

jspm install github:n-fuse/pajax

复制代码

Quick start

Fetching data via fetch()

import Pajax from 'pajax';

Pajax.fetch(url, opts)

.then(res=>{

res.body: // the response from the server

res.ok: // true

}, res=>{

// called only on network errors

res.ok; // false

res.error; // the error

});

复制代码

Fetching data via get()

import Pajax from 'pajax';

Pajax.get(url, opts)

.noCache() // See 'Configuring pajax/request instances'

.fetch()

.then(res=>{

res.body: // the response from the server

res.ok: // true

}, res=>{

// called on network and status errors

res.ok; // false

res.error; // the error

});

复制代码

Sending data

import Pajax from 'pajax';

Pajax.post(url, opts)

.attach(body)

.fetch()

.then(res=>{

res.body: // the response from the server

res.ok: // true

}, res=>{

// called on network and status errors

res.ok; // false

res.error; // the error

});

复制代码

Parameters

url (string) - the absolute or relative URL for this request

opts (object) - set of key/value pairs to configure the ajax requests

body (mixed) - the data to be sent

Usage

Fetching data

The basic fetch() is similar to the standard Fetch specification

import Pajax from 'pajax';

Pajax.fetch(url, opts)

.then(res=>{

res.body: // the response from the server

res.ok: // true

}, res=>{

// called only on network errors

res.ok; // false

res.error; // the error

});

复制代码

The returned promise will not reject any error status codes.

Call Pajax.checkStatus() after fetch() to do so.

Pajax.fetch(url, opts)

.then(Pajax.checkStatus())

.then(res=>{

res.body: // the response from the server

res.ok: // true

}, res=>{

// called on network and status errors

res.ok; // false

res.error; // the error

});

复制代码

Create a pajax instance

Creating an instance allows to modify the default options off fetch() requests.

import Pajax from 'pajax';

var pajax = new Pajax(opts);

pajax.fetch(...);

复制代码

Options

Most options are very similar to the Fetch options.

method (string) - GET, POST, PUT, PATCH, DELETE, HEAD

cache (string) - default, no-cache - no-cache will add a _={timestamp} query parameter to avoid caching

queryParams (object) - set of key/value pairs that are added as query parameters to the url

responseType (string) - the expected result type from the server. Request is always rejected, when the response body does not match the expected type.

contentType (string) - the content type of the data sent to the server

headers (object) - set of key/value pairs that are added to the request header

progress (function) - callback for the the upload progress

timeout (integer) - number of milliseconds to wait for a response

credentials (string) - same-origin, include - Use include to send cookies in a CORS request.

baseURL (string) - base for requests with relative urls

Requests

A Request instance represents a request to a specific resource and can be provided as a fetch() argument.

The constructor has the same signature as the fetch method.

var req = new Pajax.Request(url, opts);

pajax.fetch(req).then(...);

复制代码

Request objects can also be created with the request() method on a pajax instance.

They inherit the default options of the pajax instance.

var pajax = new Pajax(opts1);

// Merges opts1 with opts2 in request

var req = pajax.request(url, opts2);

pajax.fetch(req).then(...);

复制代码

There are helper methods to create requests for common HTTP methods:

get, post, put, patch, delete and head.

checkStatus() is automatically called when using them.

var req = pajax.post(url, opts);

pajax.fetch(req)

.then(res=>{

res.body: // the response from the server

res.ok: // true

}, res=>{

// called on network and status errors

res.ok; // false

res.error; // the error

});

复制代码

Instead of calling pajax.fetch(request) you can call fetch directly on a request

without an argument.

pajax.fetch(pajax.post(url, opts)).then(...);

// is the same as

pajax.post(url, opts).fetch().then(...);

复制代码

Configuring pajax/request instances

It is also possible to set options by chaining methods in a request before invoking fetch()

pajax.put('/url')

.header({'Accept-Language': 'en'}) // headers via object

.header('Accept-Language', 'en') // header via key-value

.query({'foo': 'bar'}) // query parameters via object

.query('foo', 'bar') // query parameter via key-value

.noCache() // Sets cache to `no-cache`

.withCredentials() // Sets credentials to `include`

.setResponseType('application/json')

.setContentType('application/json')

.onProgress(req, event=>{

...

})

.setTimeout(5000)

.attach({ foo: 'bar' })

.fetch()

.then(...);

复制代码

Call the methods on the pajax instance to set the options for every request.

var pajax = new Pajax()

.header('Accept-Language', 'en')

.noCache();

pajax.get(url).fetch().then(...);

复制代码

Request/Response transformations

There are hooks to register transformation tasks for requests and responses

pajax.get(url)

.before(req=>{

req; // request object

// do some stuff before a request is sent

})

.before(req=>{

req; // request object

// do more stuff before a request is sent

})

.after(res=>{

res; // response object

// do some stuff after a request

})

.afterSuccess(res=>{

res; // response object

// do some stuff after a successful request

})

.afterFailure(res=>{

res; // response object

// do some stuff after a failed request

})

.fetch() // send request

.then(res=>{

// res.body: the response from the server

});

复制代码

Call the methods on the pajax instance to register transformation tasks for every request.

var pajax = new Pajax().before(req=>{

// do some stuff before a request is sent

});

pajax.get(url).fetch().then(...);

复制代码

Modifying the Pajax/Request/Response Class

You can easily extend the Pajax, Request and Response Class to implement custom methods

or override the existing ones.

// Our external authenticator

let auth = {token: 'g54gsfdgw34qj*9764w3'};

// Custom pajax class

class MyPajax extends Pajax {

// Add new method for authenticated GETs

getAuth(...args) {

return super.get(...args).authenticate();

}

// Override delete()

// All DELETE requests should be authenticated

delete(...args) {

return super.delete(...args).authenticate();

}

}

// Custom request class

MyPajax.Request = class extends Pajax.Request {

// Adds the token to the request header

authenticate() {

return this.header('authorization', `Bearer ${this.opts.auth.token}`);

}

}

// Custom response class

MyPajax.Response = class extends Pajax.Response {

// Checks if we are authenticated

get isAuthenticated() {

return this.headers['X-authentication-level'] > 0;

}

}

var pajax = new MyPajax({auth});

// token added by getAuth()

pajax.getAuth(url)

.fetch()

.then(res => {

// res.isAuthenticated = true

});

// no token added

pajax.get(url)

.fetch()

.then(res => {

// res.isAuthenticated = false

});

// token added manually

pajax.post(url)

.authenticate() // Adds bearer token to request

.fetch()

.then(res => {

// res.isAuthenticated = true

});

// token added by delete() override

pajax.delete(url)

.fetch()

.then(res => {

// res.isAuthenticated = true

});

复制代码

There are also some predefined classes:

// For jsons

var pajax = new Pajax.JSON(opts);

pajax.get('/url/to/json').fetch().then(res=>{

res.body; /// js object

}, res=>{

...

});

复制代码

// For url encoded requests

var pajax = new Pajax.URLEncoded(opts);

pajax.post('/url', {foo:'bar'}).fetch().then(res=>{

...

}, res=>{

...

});

复制代码

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值