Issue
I want to add a record to a MongoDB collection with the new MongoDB Data API. It works perfectly with Postman or curl with this code:
curl --location --request POST 'https://data.mongodb-api.com/app/<Data API App ID>/endpoint/data/beta/action/insertOne' \
--header 'Content-Type: application/json' \
--header 'Access-Control-Request-Headers: *' \
--header 'api-key: <Data API Key>' \
--data-raw '{
"dataSource": "<cluster name>",
"database": "<database name>",
"collection": "<collection name>",
"document": {
"firstname": "John",
"lastname": "Doe",
"email": "[email protected]"
}
}'
but fails when I use fetch:
function addUser(event){
event.preventDefault();
fetch('https://data.mongodb-api.com/app/<Data API App ID>/endpoint/data/beta/action/insertOne', {
method:'POST',
mode: 'no-cors',
headers: {
'Content-type':'application/json',
'Access-Control-Request-Headers': '*',
'api-key': '<Data API Key>',
},
body:
{
"dataSource": "<cluster name>",
"database": "<database name>",
"collection": "<collection name>",
"document":
{
"firstname": "John",
"lastname": "Doe",
"email": "[email protected]"
}
}
})
res.render('homepage')
}
Error in MongoDB log: Error:
"no authentication methods were specified"
Where is the error in my code?
I am a beginner with fetch to MongoDB Data API.
Solution
Problem solved! Had to add this on top of my routes:
router.use(express.json());
Hope this might help for someone else too :)
Answered By - Herman Answer Checked By - Marilyn (WPSolving Volunteer)