0

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

  • Using `no-cors` in `fetch` means, it doesn't return a response body. If the server doesn't set CORS headers, the browser can't directly communicate with it. That's the reason, you only find solutions using a backend (e.g. Node.js). It's the only way. – Thomas Sablik Jan 19 '23 at 21:07
  • Thanks for enlightening me on no-cors. I'm just wondering that if it can be done from an Arduino like device, there should be a way to do it from JS too. – 65Cadillac Jan 19 '23 at 21:15
  • It is possible to do it with JS. Node.js is a JS runtime environment. It's not possible from a browser. CORS is a browser security feature. – Thomas Sablik Jan 19 '23 at 21:26

0 Answers0