I have a Vuejs application from which I want to fetch some data from MongoDB.
I'm using MongoDB API, so I can host the static files on my hosting, serverless.
Using axios I generate the following query:
getData() {
const data = JSON.stringify({
"collection": "≤MY_COLLECTION>",
"database": "≤MY_DATABASE>",
"dataSource": "Cluster0",
"projection": {
"_id": 1
}
});
const config = {
method: 'post',
url: 'https://data.mongodb-api.com/app/data-spysy/endpoint/data/beta/action/findOne',
headers: {
'Content-Type': 'application/json',
'Access-Control-Request-Headers': '*',
'api-key': '<MY_API_KEY>',
},
data: data
};
axios(config)
.then(function (response) {
console.log(JSON.stringify(response.data));
})
.catch(function (error) {
console.log('Error: ',error);
});
}
When I run it, I get the following error from axios
Request from another origin blocked: Same-origin policy prevents reading the remote resource at https://data.mongodb-api.com/app/.../findOne (reason: missing CORS header 'Access-Control-Allow-Origin'). Status code: 204.
Solicitud de origen cruzado bloqueada: La misma política de origen no permite la lectura de recursos remotos en https://data.mongodb-api.com/app/data-spysy/endpoint/data/beta/action/findOne. (Razón: Solicitud CORS sin éxito). Código de estado: (null)
If I make the query with cURL in the same pc it works without problems:
curl --location --request POST 'https://data.mongodb-api.com/app/data-spysy/endpoint/data/beta/action/findOne' \
--header 'Content-Type: application/json' \
--header 'Access-Control-Request-Headers: *' \
--header 'api-key: ≤MY_API_KEY>' \
--data-raw '{
"collection":"≤MY_COLLECTION>",
"database":"≤MY_DATABASE>",
"dataSource":"Cluster0",
"projection": {"_id": 0}
}'