I've written an Arduino (ESP32) code that can access MongoDB Atlas API using HTTPS POST. This ESP32 microcontroller inserts measurement data into a MongoDB Atlas database. However MongoDB provides charts that can access data directly, these charts are somewhat limited, so I would like to use charts.js or similar instead. Accessing MongoDB Atlas from the ESP32 was pretty easy and works fine, so I thought that fetching Atlas data with JavaScript would be even easier. The ESP32 code can do all kind of CRUD operations and properly handle responses.
I'm looking for a simple HTML/CSS/JS frontend-only solution. All my Google searches resulted in Node.js solutions, generally using the Mongoose library.
I'd appreciate if someone could tell what's wrong with my code and if there is any solution to read data from Atlas without having to implement a Node.js backend.
async function makeRequest() {
let url =
"https://data.mongodb-api.com/app/data-sqcsd/endpoint/data/v1/action/insertOne";
let data = {
dataSource: "Cluster0",
database: "testdb",
collection: "testcollection",
document: { "test": "test text to be inserted" }
};
let res = await fetch(url, {
mode: "no-cors",
method: "POST",
headers: {
"Content-Type": "application/json",
"api-key":
"6Lfrjilpn4f4BXikSTFekSi1Usx8tOtgKqOzdvskN6CwdFJimPYqmpRdRn3NuwRH",
},
body: JSON.stringify(data),
});
if (res.ok) {
let ret = await res.json();
return JSON.parse(ret.data);
} else {
return `HTTP error: ${res.status};
}
}
makeRequest().then((data) => {
console.log(data);
});
Chrome console output: Failed to load resource: the server responded with a status of 400 () HTTP error: 0