A lightweight and flexible JavaScript class for making HTTP requests with support for:
- FormData (including nested objects)
- JSON payloads
- Request timeouts
- Centralized error handling
- Automatic response parsing (
json
,text
,blob
) - Optional
returnFullResponseOnError
Simply copy the Fetcher.js
file into your project:
# Or clone the repository
git clone https://github.com/Simone4e/FetcherJS.git
Then import it:
import Fetcher from './Fetcher.js';
- ✅ POST/GET with
FormData
orJSON
- ✅ Automatic query string for GET requests
- ✅ Timeout support via
AbortController
- ✅ Centralized HTTP error handling
- ✅ Optional full response return on error
- ✅ Lightweight and dependency-free
const fetcher = new Fetcher('/api/', {
'Authorization': 'Bearer your-token'
});
await fetcher.request({
method: 'POST',
url: 'user/create',
data: {
name: 'Alice',
email: '[email protected]'
}
});
await fetcher.request({
method: 'GET',
url: 'user/list',
data: { page: 1, search: 'john' }
});
await fetcher.request({
method: 'POST',
url: 'auth/login',
headers: {
'Content-Type': 'application/json'
},
data: {
email: '[email protected]',
password: 'password'
}
});
- baseURL (string): Prefix added to all URLs.
- defaultHeaders (object): Default headers for all requests.
Option | Type | Description |
---|---|---|
method | string | HTTP method (default: 'POST' ) |
url | string | Endpoint (appended to baseURL) |
data | object | Data to send (FormData or JSON) |
headers | object | Additional headers |
timeout | number | Request timeout in ms (default: 10000) |
responseType | string | 'json' , 'text' , or 'blob' (default: 'json' ) |
returnFullResponseOnError | boolean | If true, returns { data, response } on error |
Returns: Parsed response or full error response if returnFullResponseOnError
is true.
Centralized error handler. You can customize behavior based on the HTTP status code.
401
: Not authenticated403
: Authenticated but unauthorized422
: Validation errors (shows alert)- Default: logs to console
Converts a nested object into a valid FormData
instance.
const fd = new FormData();
Fetcher.appendFormData(fd, {
user: {
name: 'Mario',
address: { city: 'Rome' }
}
});
const result = await fetcher.request({ method: 'POST', url: 'user/update', data: { name: 'Test' }, responseType: 'json', returnFullResponseOnError: true });
if (result.response && !result.response.ok) { console.error('Error:', result.data); } else { console.log('Success:', result); }
MIT License © Rossaini Simone