Constructor
new Body(textBodyopt)
Creates a new instance of the Body class.
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
textBody | string | <optional> | null | Optional. The text body of the request or response. |
Methods
parseJSON() → {object|null}
Parses the body as JSON.
Returns:
- The parsed JSON body, or null if not available or parsing failed.
- Type:
- object |
null
Example
// Example HTTP response body as a JSON string.
const jsonBody = JSON.stringify({
user: 'alice',
posts: ['post1', 'post2']
});
// Create an instance of the Body class with the JSON string.
const bodyInstance = new Body(jsonBody);
// Use parseJSON() to parse the body text as JSON.
const json = bodyInstance.parseJSON();
if (json) {
console.log('Parsed JSON:' + json);
console.log('User:' + json.user); // Accessing a property from the parsed JSON.
} else {
console.error('Failed to parse JSON');
}
parseText() → {string|null}
Parses the body as text.
Returns:
- The parsed text body, or null if not available.
- Type:
- string |
null
Example
// Example HTTP response body as a JSON string.
const jsonBody = JSON.stringify({
user: 'alice',
posts: ['post1', 'post2']
});
// Create an instance of the Body class with the JSON string.
const bodyInstance = new Body(jsonBody);
// Use parseText() to get the text representation of the body.
const text = bodyInstance.parseText();
console.log('Parsed Text:' + text);
parseURLSearchParams() → {URLSearchParams|null}
Parses the body as URLSearchParams.
Returns:
- The parsed URLSearchParams body, or null if not available.
- Type:
- URLSearchParams |
null
Example
// Example HTTP response body as a URL search string.
const searchBody = 'sort=desc&filter=published';
// Create another instance of the Body class with the URL search string.
const searchBodyInstance = new Body(searchBody);
// Use parseURLSearchParams() to parse the body text as URLSearchParams.
const searchParams = searchBodyInstance.parseURLSearchParams();
if (searchParams) {
console.log('Parsed URL Search Params:' + searchParams.toString());
// Accessing query parameters.
console.log('Sort Order:' + searchParams.get('sort'));
} else {
console.error('Failed to parse URLSearchParams');
}