How can I fetch data from a MongoDB database using an Express API?
I am trying to use JavaScript for this task.
$scope.nmr=function(){
$http.get("http://127.0.0.1:8081/Blogs")
.then(function (response)
{$scope.Blog = ((response.data).slice(0,8));
});
};
This is the HTML code that I am working with:
<span style=" font-size:25px; ">معبد حتبسوت</span>
<span style="margin-right:10%;" ng-repeat="x in Blog">
<div star-rating rating-value="x.AvgRate" max="5"></div>
</span>
In my server.js/Api file, I have the following code snippet:
app.get('/Blogs', function (req, res) {
MongoClient.connect(url, function (err, db) {
if (err) {
console.log('Unable to connect to the mongoDB server. Error:', err);
} else {
//We are connected.
console.log('Connection established to', url);
db.collection('Blog').find().toArray(function (err, result) {
if (err) throw err
console.log(result);
res.end( JSON.stringify(result));
})
}
});
})
Although the data is returned in the console, I am encountering an error when trying to access it in the browser:
[database server][1]
The error message reads: "Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at . (Reason: CORS header ‘Access-Control-Allow-Origin’ missing)"