API Res: Node.js HTTP(S) Request Library
API Res is a lightweight Node.js HTTP(S) request library specifically designed for interacting with Nodal API services. Currently at version 1.0.3, it provides a simple interface for making RESTful API calls within a Node.js environment. While the exact release cadence is not specified, its minimalistic design suggests a focus on stability rather than frequent feature additions. Key differentiators include its explicit integration with Nodal APIs and a straightforward request syntax, aiming for ease of use in projects that leverage the Nodal framework. It serves as a foundational utility for consuming APIs, particularly those built with Nodal, by abstracting standard HTTP request complexities.
Common errors
-
Error [ERR_REQUIRE_ESM]: require() of ES Module /path/to/node_modules/api-res/index.js from /your/app.js not supported.
cause Attempting to `require()` an ESM-only module, or using `import` syntax for a CJS-only module.fixEnsure your project is configured for CommonJS modules (e.g., no `"type": "module"` in `package.json` or rename `.js` files to `.mjs` for ESM). For `api-res`, stick to `require()`. -
(node:XXXXX) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'body' of undefined
cause An asynchronous request failed, but the promise rejection was not caught, or the `response` object was null/undefined due to an unhandled network error.fixAlways use `try...catch` blocks with `async/await` or `.catch()` with Promises to handle potential errors gracefully. Check if `error.response` exists before accessing its properties. -
Error: connect ECONNREFUSED 127.0.0.1:3000
cause The target API server is not running or is not accessible at the specified address and port.fixVerify the API server is online, listening on the correct port, and that there are no firewall rules blocking the connection.
Warnings
- gotcha The library appears to be focused on CommonJS. Using 'import' syntax (ESM) directly may lead to runtime errors or require bundlers/transpilers to resolve.
- gotcha As a relatively lightweight and possibly less actively maintained library (last update appears to be around v1.0.x), ensure it's compatible with your current Node.js version and that any security concerns in underlying HTTP modules are mitigated if used in production.
- gotcha Error handling for network issues (e.g., DNS resolution failure, connection timeout) versus application-level API errors (e.g., 404, 500) might require careful inspection of the `error` object structure returned by `api-res`.
Install
-
npm install api-res -
yarn add api-res -
pnpm add api-res
Imports
- apiRes
import apiRes from 'api-res';
const apiRes = require('api-res'); - get
import { get } from 'api-res';const { get } = require('api-res'); - post
import { post } from 'api-res';const { post } = require('api-res');
Quickstart
const apiRes = require('api-res');
async function fetchData() {
try {
// Example GET request
const getResponse = await apiRes.get('http://localhost:3000/api/users');
console.log('GET Response Body:', getResponse.body);
console.log('GET Status Code:', getResponse.statusCode);
// Example POST request with data and headers
const payload = { name: 'Alice', email: 'alice@example.com' };
const postOptions = {
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${process.env.API_KEY ?? ''}` // Use env var for sensitive data
},
json: true // Instructs library to send and expect JSON
};
const postResponse = await apiRes.post('http://localhost:3000/api/users', payload, postOptions);
console.log('POST Response Body:', postResponse.body);
console.log('POST Status Code:', postResponse.statusCode);
} catch (error) {
console.error('An error occurred during API request:', error.message);
if (error.response) {
console.error('Error Response Body:', error.response.body);
console.error('Error Status Code:', error.response.statusCode);
}
}
}
fetchData();