Hello, I have a simple static website using HTML, CSS and JS. I am trying to connect to my MongoDB instance and have been running into the following error:
Access to fetch at 'https://us-west-2.aws.data.mongodb-api.com/app
/data-rrmea/endpoint/data/v1/action/find'
from origin 'http://localhost:63342' has been blocked by CORS policy:
Response to preflight request doesn't pass access control check: No
'Access-Control-Allow-Origin' header is present on the requested
resource. If an opaque response serves your needs, set the request's
mode to 'no-cors' to fetch the resource with CORS disabled.
My code is as follows:
const endpointUrl = `https://us-west-2.aws.data.mongodb-api.com/app/data-rrmea/endpoint/data/v1/action/find`;
const headers = {
'Content-Type': 'application/json',
'api-key': `${apiKey}`,
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET,HEAD,OPTIONS,POST,PUT,DELETE',
'Access-Control-Allow-Headers': 'Origin, X-Requested-With, Content-Type, Accept, Authorization'
};
var payload = {
'dataSource': 'Cluster0',
'database': 'GoogleForms',
'collection': 'reponses'
};
const options = {
method: 'POST',
headers,
payload: JSON.stringify(payload)
};
fetch(endpointUrl, options)
.then(response => response.json())
.then(data => {
const dataList = document.getElementById('data-list');
console.log(JSON.stringify(data));
data.forEach(item => {
const li = document.createElement('li');
li.textContent = JSON.stringify(item);
dataList.appendChild(li);
});
})
.catch(error => console.log(error));
My application does not use NodeJS and would like to stick to it.