HttpClient is a simple HTTP client for making asynchronous HTTP requests in JavaScript using built-in fetch api. It supports various HTTP methods such as GET
, POST
, PUT
, and DELETE
.
This utility function, used to initiate HTTP requests, was copied/pasted/modified from a version originally created by Walter Kimaro.
- using npm
npm i @bonny-kato/httpclient
- using yarn
yarn add @bonny-kato/httpclient
import HttpClient from "@bonny-kato/httpclient";
const httpClient = new HttpClient({
baseUrl: 'https://api.example.com',
headers: {
'Authorization': 'Bearer YOUR_ACCESS_TOKEN'
}
});
Makes an asynchronous GET request to the specified endpoint.
httpClient.get(endpoint);
Make a POST request to the specified endpoint with the provided data
httpClient.post(endpoint, data);
Sends a PUT request to the specified endpoint with the provided data.
httpClient.put(endpoint, data);
Removes a resource from the server.
httpClient.remove(endpoint);
// Get users
const getUsers = () => {
return httpClient.get("/users");
}
// Add user
const addUser = (data: User) => {
return httpClient.post("/users", data);
}
// Update user
const updateUser = (userId: string, data: User) => {
return httpClient.put(`/users/${userId}`, data);
}
// Remove user
const removeUser = (userId: string) => {
return httpClient.remove(`/users/${userId}`);
}
export interface IHeaders {
"Content-Type"?: "multipart/form-data" | "application/json" | undefined;
Authorization?: string;
}
export interface IConfig {
baseUrl: string;
headers?: IHeaders;
}
export type HttpMethod = "GET" | "POST" | "PUT" | "DELETE";
Create a new instance of HttpClient.
-
config
: An object containing configuration options.-
baseUrl
(string): The base URL for API requests. -
headers
(IHeaders): Optional. Custom headers to be included in each request.
-
Makes a generic HTTP request.
-
method
(HttpMethod): The HTTP method for the request. -
endpoint
(string): The endpoint URL. -
data
(any): Optional. Data to be sent in the request body.
Makes an asynchronous GET request.
-
endpoint
(string): The endpoint URL.
Makes a POST request.
-
endpoint
(string): The endpoint URL. -
data
(object): Data to be sent in the request body.
Sends a PUT request.
-
endpoint
(string): The endpoint URL. -
data
(object): Data to be sent in the request body.
Removes a resource.
-
endpoint
(string): The endpoint URL.
This project is licensed under the MIT License