I am trying to use a shell script to save data to mongodb then send the same to elasticsearch for analysis. Below is a psudo code in the shell script that illustrate the issue.
mongo $mongo_conn --eval "
// other javascritp code
db.collection.insertOne(insertData);
http_post_to_elasticsearch(url,insertData);
function http_post_to_elasticsearch(url,insertData){
// which http_post() method can work here?
// both fetch and xhr are undefined
// tried installing npm install -g xmlhttprequest but 'require' is also undefined
}
Below are the functions that have tried but seem not to be supported
async function http_post(url = '', data = {}) {
print('starting http_post()')
// Default options are marked with *
const response = await fetch(url, {
method: 'POST', // *GET, POST, PUT, DELETE, etc.
mode: 'cors', // no-cors, *cors, same-origin
cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
credentials: 'same-origin', // include, *same-origin, omit
headers: {
'Content-Type': 'application/json'
// 'Content-Type': 'application/x-www-form-urlencoded',
},
redirect: 'follow', // manual, *follow, error
referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
body: JSON.stringify(data) // body data type must match "Content-Type" header
});
return response.json(); // parses JSON response into native JavaScript objects
}
async function xhr_post(url = '', data = {}) {
const xhr = require('xmlhttprequest').XMLHttpRequest;
// const xhr = new XMLHttpRequest();
// listen for `load` event
xhr.onload = async () => {
// print JSON response
if (xhr.status >= 200 && xhr.status < 300) {
// parse JSON
const response = JSON.parse(xhr.responseText);
printjson(response);
// return response;
}
};
// create a JSON object
const json = data;
// open request
xhr.open('POST', url);
// set `Content-Type` header
xhr.setRequestHeader('Content-Type', 'application/json');
// send rquest with JSON payload
xhr.send(JSON.stringify(json));
}