Axios wrapper
Node-RED Axios Wrapper
Overview
This provides a generic wrapper function for Axios, enabling you to make HTTP requests within Node-RED with configurations similar to those used in Postman. The function follows the subscribe pattern and is designed to be easily integrated into your Node-RED workflows.
Parameters
config
(Object): The request configuration object that should include properties likeurl
,method
,headers
,params
, anddata
.
Returns
A Promise that resolves with the response data as a JSON object.
Usage in Node-RED Subflow
The function is executed using the subscribe pattern, which means it will process incoming messages (msg.payload
) containing request configurations:
return axiosWrapper(msg.payload)
.then(responseData => {
msg.payload = responseData;
return msg;
})
.catch(error => {
msg.payload = { status: 'error', message: error };
return msg;
});
Functionality
Header Configuration:
- Merges any headers provided in the
config
with a default'Content-Type'
of'application/json'
.
- Merges any headers provided in the
Request Configuration:
- Constructs the request configuration using properties from the input config (
url
,method
,headers
,params
, anddata
).
- Constructs the request configuration using properties from the input config (
Debug Logging (if enabled):
- Logs the request configuration to the Node-RED console if debugging is enabled globally.
HTTP Request Execution:
- Uses Axios to make the HTTP request.
- Resolves with response data on success.
- Rejects with an error message if the request fails.
Example Input Message (msg.payload
)
{
"url": "https://api.example.com/data",
"method": "POST",
"headers": {
"Authorization": "Bearer <token>"
},
"data": {
"key1": "value1"
}
}
Example Output Message (msg.payload
)
- Success: Contains the response data from the API.
- Error: Contains a status of 'error' and the error message.
Installation
- Clone this repository or download the subflow file directly.
- Import the subflow into your Node-RED instance via the "Import" feature in the Node-RED UI.
Dependencies
- Axios: Ensure you have Axios installed in your Node-RED environment to use this wrapper function.
npm install axios
Configuration
- The
config
object should contain at least aurl
and amethod
. Other properties likeheaders
,params
, anddata
are optional but commonly used.
Debugging
Set the global debug setting in Node-RED to enable logging of request configurations:
global.set('debug', true);
This will print out the request configuration being sent via Axios to help with debugging issues.
This subflow function is designed to simplify making HTTP requests within Node-RED by leveraging Axios while maintaining flexibility similar to Postman configurations.
[{"id":"48bf9a1d19c90a0e","type":"subflow","name":"Axios","info":"\n# Node-RED Axios Wrapper\n\n## Overview\n\nThis provides a generic wrapper function for Axios, enabling you to make HTTP requests within Node-RED with configurations similar to those used in Postman. The function follows the subscribe pattern and is designed to be easily integrated into your Node-RED workflows.\n\n## Parameters\n\n- `config` (Object): The request configuration object that should include properties like `url`, `method`, `headers`, `params`, and `data`.\n\n## Returns\n\nA Promise that resolves with the response data as a JSON object.\n\n## Usage in Node-RED Subflow\n\nThe function is executed using the subscribe pattern, which means it will process incoming messages (`msg.payload`) containing request configurations:\n\n```javascript\nreturn axiosWrapper(msg.payload)\n .then(responseData => {\n msg.payload = responseData;\n return msg;\n })\n .catch(error => {\n msg.payload = { status: 'error', message: error };\n return msg;\n });\n```\n\n## Functionality\n\n1. **Header Configuration**:\n - Merges any headers provided in the `config` with a default `'Content-Type'` of `'application/json'`.\n\n2. **Request Configuration**:\n - Constructs the request configuration using properties from the input config (`url`, `method`, `headers`, `params`, and `data`).\n\n3. **Debug Logging** (if enabled):\n - Logs the request configuration to the Node-RED console if debugging is enabled globally.\n\n4. **HTTP Request Execution**:\n - Uses Axios to make the HTTP request.\n - Resolves with response data on success.\n - Rejects with an error message if the request fails.\n\n## Example Input Message (`msg.payload`)\n\n```json\n{\n \"url\": \"https://api.example.com/data\",\n \"method\": \"POST\",\n \"headers\": {\n \"Authorization\": \"Bearer <token>\"\n },\n \"data\": {\n \"key1\": \"value1\"\n }\n}\n```\n\n## Example Output Message (`msg.payload`)\n\n- **Success**: Contains the response data from the API.\n- **Error**: Contains a status of 'error' and the error message.\n\n## Installation\n\n1. Clone this repository or download the subflow file directly.\n2. Import the subflow into your Node-RED instance via the \"Import\" feature in the Node-RED UI.\n\n## Dependencies\n\n- Axios: Ensure you have Axios installed in your Node-RED environment to use this wrapper function.\n\n```bash\nnpm install axios\n```\n\n## Configuration\n\n- The `config` object should contain at least a `url` and a `method`. Other properties like `headers`, `params`, and `data` are optional but commonly used.\n\n## Debugging\n\nSet the global debug setting in Node-RED to enable logging of request configurations:\n\n```javascript\nglobal.set('debug', true);\n```\n\nThis will print out the request configuration being sent via Axios to help with debugging issues.\n\n---\n\nThis subflow function is designed to simplify making HTTP requests within Node-RED by leveraging Axios while maintaining flexibility similar to Postman configurations.\n","category":"network","in":[{"x":100,"y":120,"wires":[{"id":"22efe229946607a2"}]}],"out":[{"x":420,"y":120,"wires":[{"id":"22efe229946607a2","port":0}]}],"env":[],"meta":{"module":"node-red-axios-wrapper","version":"1.0.1","author":"[email protected]","desc":"AxiosWrapper","keywords":"axios,http,rest,api","license":"Apache-2.0"},"color":"#2E8B57","inputLabels":["Payload"],"outputLabels":["Response"],"icon":"node-red/link-call.svg"},{"id":"22efe229946607a2","type":"function","z":"48bf9a1d19c90a0e","name":"Api Call","func":"/**\n * Generic Axios Wrapper that accepts request configuration similar to Postman\n *\n * @param {Object} config - The request configuration object.\n * @returns {Promise<Object>} A promise resolving with the response data as JSON.\n */\nfunction axiosWrapper(config) {\n return new Promise((resolve, reject) => {\n const headers = {\n ...config.headers,\n 'Content-Type': config.headers?.['Content-Type'] || 'application/json'\n };\n\n const requestConfig = {\n url: config.url,\n method: config.method.toUpperCase() || 'get',\n headers: headers\n };\n\n if (config.params) {\n requestConfig.params = config.params;\n }\n\n if (config.data) {\n requestConfig.data = config.data;\n }\n if (global.get('debug')) {\n node.warn('Calling axios:')\n node.warn(requestConfig)\n }\n axios(requestConfig)\n .then(response => resolve(response.data))\n .catch(error => reject(error));\n });\n}\n\n// Main execution using subscribe pattern\nreturn axiosWrapper(msg.payload)\n .then(responseData => {\n msg.payload = responseData;\n node.status({fill:\"green\",shape:\"ring\",text:\"Pass\"});\n return msg;\n })\n .catch(error => {\n msg.payload = { status: 'error', message: error };\n node.status({fill:\"red\",shape:\"\",text:\"Fail\"});\n return msg;\n });","outputs":1,"timeout":0,"noerr":0,"initialize":"","finalize":"","libs":[{"var":"axios","module":"axios"}],"x":240,"y":120,"wires":[[]],"info":"\n# Node-RED Axios Wrapper\n\n## Overview\n\nThis provides a generic wrapper function for Axios, enabling you to make HTTP requests within Node-RED with configurations similar to those used in Postman. The function follows the subscribe pattern and is designed to be easily integrated into your Node-RED workflows.\n\n\n\n## Parameters\n\n- `config` (Object): The request configuration object that should include properties like `url`, `method`, `headers`, `params`, and `data`.\n\n## Returns\n\nA Promise that resolves with the response data as a JSON object.\n\n## Usage in Node-RED Subflow\n\nThe function is executed using the subscribe pattern, which means it will process incoming messages (`msg.payload`) containing request configurations:\n\n```javascript\nreturn axiosWrapper(msg.payload)\n .then(responseData => {\n msg.payload = responseData;\n return msg;\n })\n .catch(error => {\n msg.payload = { status: 'error', message: error };\n return msg;\n });\n```\n\n## Functionality\n\n1. **Header Configuration**:\n - Merges any headers provided in the `config` with a default `'Content-Type'` of `'application/json'`.\n\n2. **Request Configuration**:\n - Constructs the request configuration using properties from the input config (`url`, `method`, `headers`, `params`, and `data`).\n\n3. **Debug Logging** (if enabled):\n - Logs the request configuration to the Node-RED console if debugging is enabled globally.\n\n4. **HTTP Request Execution**:\n - Uses Axios to make the HTTP request.\n - Resolves with response data on success.\n - Rejects with an error message if the request fails.\n\n## Example Input Message (`msg.payload`)\n\n```json\n{\n \"url\": \"https://api.example.com/data\",\n \"method\": \"POST\",\n \"headers\": {\n \"Authorization\": \"Bearer <token>\"\n },\n \"data\": {\n \"key1\": \"value1\"\n }\n}\n```\n\n## Example Output Message (`msg.payload`)\n\n- **Success**: Contains the response data from the API.\n- **Error**: Contains a status of 'error' and the error message.\n\n## Installation\n\n1. Clone this repository or download the subflow file directly.\n2. Import the subflow into your Node-RED instance via the \"Import\" feature in the Node-RED UI.\n\n## Dependencies\n\n- Axios: Ensure you have Axios installed in your Node-RED environment to use this wrapper function.\n\n```bash\nnpm install axios\n```\n\n## Configuration\n\n- The `config` object should contain at least a `url` and a `method`. Other properties like `headers`, `params`, and `data` are optional but commonly used.\n\n## Debugging\n\nSet the global debug setting in Node-RED to enable logging of request configurations:\n\n```javascript\nglobal.set('debug', true);\n```\n\nThis will print out the request configuration being sent via Axios to help with debugging issues.\n\n---\n\nThis subflow function is designed to simplify making HTTP requests within Node-RED by leveraging Axios while maintaining flexibility similar to Postman configurations.\n```"},{"id":"feea3d48ee786278","type":"subflow:48bf9a1d19c90a0e","z":"f6f2187d.f17ca8","name":"","x":370,"y":220,"wires":[[]]}]