phax v4.0.2
phax
phax is a lightweight HTTP client based on the browser Fetch API;
Language
- English
- 简体中文
Installing
npm install phax --save
// or
yarn add phaxUsage
Temporarily only supports GET/POST/PUT/PATCH/HEAD/DELETE method. The default value:
{
credentials: 'same-origin',
method: 'GET'
}import phax from 'phax'; // ES6 module
window.phax.get;
window.phax.post;
// or
phax.get;
phax.post;
// add interceptor
// add request interceptor
phax.interceptors.request(function (params) {
params.json.b = 2;
return params;
});
// add response interceptor, first function response interceptor,second function error interceptor
phax.interceptors.response(
function (params) {
return params;
},
(err: PhaxError) => {}
);
phax
.get()
.then(function (res) {
// Response.ok == true
console.log(res);
})
.catch(function (err) {
if (err.name === 'StatusError') {
// HTTP statuses error
console.log(err.statusCode + ' & ' + err.message);
} else {
// Network error
console.log(err);
}
});The default return value type matches by res.headers.Content-Type,egg:
if (res.headers.Content - Type === 'application/json') {
return res.json();
}Return type matching:
text/*=> textapplication/json=> jsonmultipart/form-data=> formData
Different from native API. phax's catch error contains Network error、HTTP statuses error.
For function parameters refer to fetch-polyfill or fetch
Example
GET
Performing a GET request.
import phax from 'phax';
phax({
url: '/user?id=1',
method: 'GET',
});
phax
.get('/user?id=1')
.then(function (res) {
console.log(res); // json
})
.catch(function (err) {
console.log(err);
});
// Want to use async/await? Add the `async` keyword to your outer function/method.
async function getUser() {
try {
const response = await phax.get('/user?id=12345').json();
console.log(response);
} catch (error) {
console.error(error);
}
}NOTE:
async/awaitis part of ECMAScript 2017 and is not supported in Internet Explorer and older browsers, so use with caution.
POST
Send json data.
phax.post('/post_user', { json: { name: 'LIVI' } });Using application/x-www-form-urlencoded format
To send data in the application/x-www-form-urlencoded, you can use one of the following options.
Use the URLSearchParams API as follows:
var params = new URLSearchParams(); params.append('param1', 'value1'); params.append('param2', 'value2'); phax.post('/foo', { body: params });Note that
URLSearchParamsis not supported by all browsers (see caniuse.com), but there is a polyfill available (make sure to polyfill the global environment).You can encode data using the qs library:
phax.post('/foo', { headers: { 'content-type': 'application/x-www-form-urlencoded' }, body: qs.stringify({ bar: 123 }), });If you won't use
qs, you can handle the parameters manually:var params = 'bar=123&name=LIVI&age=18'; phax.post('/foo', { headers: { 'content-type': 'application/x-www-form-urlencoded' }, body: params, });NOTE: Follow-up may consider simple support for this approach.
API
phax(url[, accept [, fetchOpts]])phax(fetchOpts)phax.get()phax.post()phax.interceptors.request()phax.interceptors.response(() => {}, () => {})
……
supported methods:get、post、put、delete、patch,all methods params same as phax()
param desc:
- url: String
- accept: String Optional The return type;The priority over default automatic matching
- json: Object Optional POST JSON body
- fetchOpts: Object The native
fetchsupported data,simultaneously compatible with the above three parameters
interceptors add request interceptor:
interceptors.request: (cb: (params: PhaxRequestConfig) => PhaxRequestConfig) => void;regist request interceptor,for each request start to operate request params.interceptors.response: (cb: (params: any) => any, err?: (err: PhaxError) => void) => void;:add response interceptor; The first function is response interceptor; The second function is error interceptor.
Promises
phax depends on a native ES6 Promise implementation to be supported. If your environment doesn't support ES6 Promises, you can polyfill. Recommended to use the jsdelivr CDN.
<script src='https://cdn.jsdelivr.net/npm/es6-promise@4.2.5/dist/es6-promise.auto.min.js'></script>fetch
phax depends on a native fetch API implementation to be supported. If your environment doesn't support fetch, you can polyfill. Recommended to use the jsdelivr CDN.
<script src='https://cdn.jsdelivr.net/npm/whatwg-fetch@3.0.0/dist/fetch.umd.min.js'></script>TypeScript
phax includes TypeScript definitions.
import phax from 'phax';
phax({ url: '/test?id=1', accept: 'json' }); // get
phax.get('/test?id=1', 'json'); // get
phax.post('/post', 'json'); // post
phax({
url: '/foo',
method: 'post',
}); // post