request Travis-ci Status GitHub license typescript | javascript | node.js Npm Version NPM Download

A simple and lightweight HTTP request library by TypeScript for browsers. The library prefers the window.fetch API and uses XMLHttpRequest without support.

Installation

Installation is done using the npm install command:

npm install -S @billjs/request

Overview

API

fetch

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.

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

Get data. It will be uses GET method to send request. This is an idempotent request.

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.

head('/api/user/1234').catch(err => console.log(err));

post

Submit data for new resource. It will be uses POST method to send request. This is a non-idempotent request.

post('/api/user', { name: 'test', age: 32 })
  .then(id => console.log(id))
  .catch(err => console.log(err));

put

Update data to replace resource. It will be uses PUT method to send request. This is an idempotent request.

put('/api/user/1234', { name: 'test', age: 22 }).catch(err => console.log(err));

patch

Similar to PUT requests, but only for local modifications. It will be uses PATCH method to send request. This is a non-idempotent request.

patch('/api/user/1234', { age: 28 })
  .then(user => console.log(user))
  .catch(err => console.log(err));

del

Delete data. It will be uses DELETE method to send request. This is an idempotent request.

del('/api/user/1234')
  .then(success => console.log(success))
  .catch(err => console.log(err));

options

The OPTIONS request, often used for cross-domain exploring. This is an idempotent request.

options('/api/user')
  .then(res => console.log(res))
  .catch(err => console.log(err));

upload

Upload form-data, such as file, etc. It will be uses Content-Type of multipart/form-data to upload form-data.

const formData = new FormData();
formData.append('image', blob);
upload('/api/upload/image', formData)
  .then(data => console.log(data))
  .catch(err => console.log(err));

catchSuccess

Global capture of all successful requests, then you can do something.

catchSuccess((data, req) => {
  console.log(data);
});

catchError

Global capture of all failed requets, then you can do something, such as to show an error message tips.

catchError((err, req) => {
  // show an error message
  Message.error(err.message);
});

catchComplete

Global capture all requests, whether successful or failed, then you can do something.

catchComplete((err, data, req) => {
  console.log(err, data);
});

parseResponse

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.

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,
  };
});

Request

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);

RequestOptions

The options for every request, you can to pass some options to Request for your case.

The option list:

RequestMethod

The HTTP request method: GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS. This property value is case insensitive, meaning that get equals GET.

RequestType

The data submission type: json, text, urlencoded, form. The corresponding Content-Type request header will be set automatically by submission type.

RequestDataType

The response data types accepted: json, text. The corresponding Content-Type response header will be set by data type.

RequestContentType

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.

RequestError

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);

ResponseData

The standardized response data structure.

But as a caller, you will be only got data property to keep it simple, and you don’t need to care about otherthings.

License

MIT License