postAsync
The postAsync
method sends an HTTP POST request with a JSON body to the specified endpoint. It supports optional route parameters, custom headers, and request cancellation via an AbortController
.
Method Signature
public async postAsync(
routeParam: string | null = null,
data: any,
headers: Headers = {},
controller: AbortController | null = null
): Promise<any>
Parameters
Name | Type | Description | Optional | Default Value |
---|---|---|---|---|
routeParam | string | null | Optional route segment to append to the base URL | Yes | null |
data | any | JSON data to send in the request body | No | N/A |
headers | Headers | Optional HTTP headers to include in the request | Yes | {} |
controller | AbortController | null | Optional controller to allow request cancellation | Yes | null |
Returns
The postAsync
method returns a Promise
that resolves to one of the following, depending on the server response:
- Parsed JSON object if the response has a Content-Type of application/json
- Plain text string if the response is text-based
- null if the server responds with HTTP status 204 No Content
Error Handling
If the request fails, the returned Promise
rejects with an error object containing:
- message: A descriptive error message
- status: HTTP status code (if available)
- statusText: HTTP status text (if available)
- responseBody: Parsed response body or raw text for further inspection
Errors can occur due to network failures, request timeouts, server errors, or manual request cancellation (via AbortController).
Example
import LunexClient from 'lunex-http';
const client = new LunexClient('https://api.example.com', {
Authorization: 'Bearer YOUR_TOKEN',
});
async function run(): Promise<void> {
try {
const newUser = {
name: 'John Doe',
email: 'john.doe@example.com',
};
const response: any = await client.postAsync('users', newUser);
console.log('User created:', response);
} catch (error: unknown) {
console.error('POST request failed:', error);
}
}
run();