A simple and lightweight HTTP request library by TypeScript for browsers.
The library prefers the window.fetch
API and uses XMLHttpRequest
without support.
Installation is done using the npm install
command:
npm install -S @billjs/request
- fetch
- get
- head
- post
- put
- patch
- del
- options
- upload
- catchSuccess
- catchError
- catchComplete
- parseResponse
HTTP request.
It's a basic request method, you can use it to send request of any methods.
The success
event will be triggered when the request succeeds, that means the catchSuccess will be called.
The error
event will be triggered when the request fails, that means the catchError will be called.
And, whether successful or failed for request, the complete
event all be triggered, that means the catchComplete all be called.
- url (
string
) request url - [data] (
any
optional
) request data, such astext
JSON
FormData
, etc. - [options] (RequestOptions
optional
) additional options, such asheaders
andtype
, etc. - return (
Promise
) it return aPromise
, you can usethen
andcatch
methods ofPromise
orasync/await
to resolve result.
Use then
and catch
methods of Promise
to resolve result.
fetch('/api/user/1234', null, { method: 'GET' })
.then(data => console.log(data))
.catch(err => console.log(err));
Use async/await
to resolve result.
async function getUser(uid: string) {
try {
const user = await fetch('/api/user/1234', null, { method: 'GET' });
console.log(user);
} catch (err) {
console.error(err);
}
}
Get data.
It will be uses GET
method to send request. This is an idempotent request.
- url (
string
) get request url - [data] (
string | object | null
) query argument. It can be either a stringified string or an object. - [options] (RequestOptions
optional
) additional options, such asheaders
andtype
, etc. - return (
Promise
)
get('/api/user/1234')
.then(user => console.log(user))
.catch(err => console.log(err));
The HEAD
method requests the same response as the GET
request, but no response body. You can use it to check if the API is working properly. This is an idempotent request.
- url (
string
) head request url - [data] (
string | object | null
) query argument. It can be either a stringified string or an object. - [options] (RequestOptions
optional
) additional options, such asheaders
andtype
, etc. - return (
Promise
)
head('/api/user/1234').catch(err => console.log(err));
Submit data for new resource. It will be uses POST
method to send request. This is a non-idempotent request.
- url (
string
) post request url - [data] (
any
) data of submitted to the server, that can be of any data type. - [options] (RequestOptions
optional
) additional options, such asheaders
andtype
, etc. - return (
Promise
)
post('/api/user', { name: 'test', age: 32 })
.then(id => console.log(id))
.catch(err => console.log(err));
Update data to replace resource. It will be uses PUT
method to send request. This is an idempotent request.
- url (
string
) put request url - [data] (
any
) data of submitted to the server, that can be of any data type. - [options] (RequestOptions
optional
) additional options, such asheaders
andtype
, etc. - return (
Promise
)
put('/api/user/1234', { name: 'test', age: 22 }).catch(err => console.log(err));
Similar to PUT
requests, but only for local modifications. It will be uses PATCH
method to send request. This is a non-idempotent request.
- url (
string
) patch request url - [data] (
any
) data of submitted to the server, that can be of any data type. - [options] (RequestOptions
optional
) additional options, such asheaders
andtype
, etc. - return (
Promise
)
patch('/api/user/1234', { age: 28 })
.then(user => console.log(user))
.catch(err => console.log(err));
Delete data. It will be uses DELETE
method to send request. This is an idempotent request.
- url (
string
) delete request url - [data] (
any
) data of submitted to the server, that can be of any data type. - [options] (RequestOptions
optional
) additional options, such asheaders
andtype
, etc. - return (
Promise
)
del('/api/user/1234')
.then(success => console.log(success))
.catch(err => console.log(err));
The OPTIONS
request, often used for cross-domain exploring. This is an idempotent request.
- url (
string
) options request url - [options] (RequestOptions
optional
) additional options, such asheaders
andtype
, etc. - return (
Promise
)
options('/api/user')
.then(res => console.log(res))
.catch(err => console.log(err));
Upload form-data, such as file, etc. It will be uses Content-Type
of multipart/form-data
to upload form-data.
- url (
string
) upload url - [data] (
FormData
) form-data - [options] (RequestOptions
optional
) additional options, such asheaders
andtype
, etc. - return (
Promise
)
const formData = new FormData();
formData.append('image', blob);
upload('/api/upload/image', formData)
.then(data => console.log(data))
.catch(err => console.log(err));
Global capture of all successful requests, then you can do something.
- cb (
(data: any, req: Request) => void
) callback function. Any successful request will call this callback function. Thereq
argument is a Request instance.
catchSuccess((data, req) => {
console.log(data);
});
Global capture of all failed requets, then you can do something, such as to show an error message tips.
- cb (
(err: RequestError, req: Request) => void
) callback function. Any failed request will call this callback function. Theerr
argument is a RequestError instance.
catchError((err, req) => {
// show an error message
Message.error(err.message);
});
Global capture all requests, whether successful or failed, then you can do something.
- cb (
(err: RequestError | null, data: any, req: Request) => void
) callback function. Any request will call this callback function.
catchComplete((err, data, req) => {
console.log(err, data);
});
The global customized HTTP response data parser, it only working for json
dataType.
You can to specify the customized parser to parse response data for yourself case. But you must have to return a correct response data by the ResponseData
structure.
If your server responsive data structure is same as ResponseData
, you don't need to specify the parse.
- cb (
ParseFunction
) parser, theresult
argument is your server responsive data. Thereturn
is an ResponseData instance.
If you have yourself response data structure, you can do it. Such as it:
parseResponse(result => {
return {
success: result.success,
statusCode: 200,
errorCode: result.error_code,
errorMessage: result.error_msg,
errorStack: result.error_stack ? result.error_stack : null,
data: result.data,
};
});
A class for HTTP request, name it as Request
. It implements all the logical details of request.
Most of the time, you don't need to create a Request
instance to send HTTP requests, just call the above shortcuts.
The declaration of constructor like this:
constructor(url: string, data: any, options: RequestOptions);
- url (
string
) request url - data (
any
) request data, such astext
JSON
FormData
, etc. - options (RequestOptions) additional options, such as
headers
andtype
, etc.
The options for every request, you can to pass some options to Request
for your case.
The option list:
- method (
RequestMethod
) The HTTP request method, see RequestMethod, defaultGET
. - headers (
RequestHeaders
) The customized HTTP request header. e.g. { "X-CSRF-Token": "123" }. It is key-value Map. - type (
RequestType
) The data submission type, see RequestType, defaultjson
. - dataType (
RequestDataType
) The response data types accepted, see RequestDataType, defaultjson
. - contentType (
RequestContentType
) The requestContent-Type
, see RequestContentType, defaultapplication/json
. - timeout (
number
) The HTTP request timeout, default0
, that means not set timeout. - useXHR (
boolean
) Is forced to use XHR(XMLHttpRequest
)? defaultfalse
, will to useswindow.fetch
API. In most cases, we recommend that you use thewindow.fetch
API. - credentials (
boolean
) Do you need to sendcookie
credentials? If it is same origin, default istrue
. Otherwise cross-domain, it isfalse
, that means not sendcookie
credentials. If you need to sendcookie
credentials for cross-domain, you need to specify it astrue
. - parse (
ParseFunction
) The customized HTTP response data parser for this request. If it is not specified, will be to uses the global customized parser or the default parser. - onProgress (
(loaded: number, total: number) => void
) The HTTP request progress event handler.
The HTTP request method: GET
, HEAD
, POST
, PUT
, PATCH
, DELETE
, OPTIONS
.
This property value is case insensitive, meaning that get
equals GET
.
The data submission type: json
, text
, urlencoded
, form
.
The corresponding Content-Type
request header will be set automatically by submission type.
- json: submit by JSON, the request
Content-Type
isapplication/json
. - text: submit by plainText, the request
Content-Type
istext/plain
. - urlencoded: submit by form of urlEncoded, the request
Content-Type
isapplication/x-www-form-urlencoded
. - form: submit by formData, the request
Content-Type
ismultipart/form-data
.
The response data types accepted: json
, text
.
The corresponding Content-Type
response header will be set by data type.
- json: accept by JSON, the response
Content-Type
isapplication/json
. - text: accpet by plainText, the response
Content-Type
istext/plain
.
The request Content-Type
, default application/json
.
If the type
is specified, the contentType corresponding to type is preferred.
If the value is false
, that means not set Content-Type
customize header. Such as, When you upload a file, you need to specify it as false
.
The RequestError class, it extends from Error.
Add status
and code
properties for it. The status
property is HTTP status. The code
property is error code of business.
The declaration of constructor like this:
constructor(status: number, code: string, msg: string, stack?: string | null);
The standardized response data structure.
- success (
boolean
) the status of success or failure. - statusCode (
number
) the status code, it same as HTTP status. - errorCode (
string
|number
) the error code, when request is failure. - errorMessage (
string
|null
) the error message, when request is failed. If request is successful, it isnull
. - errorStack (
string
|null
) the error stack, when request is failed. Only fordevelopment
mode, otherwise isnull
. - data (
any
|null
) the response data, it is any type. If request is failed, it isnull
.
But as a caller, you will be only got data
property to keep it simple, and you don't need to care about otherthings.