0

I have a problem with a method to send the information to front end, I find the docuement from mongo db and mongo send me back the information, but whem i try to send this docs appear 2 problems, the first problem is this : The Angular send a respond "No 'Access-Control-Allow-Origin' header is present on the requested resource" and the other problem is in the back end I make console.log with the documents from data base and the documents show in console, but whem i try to send the object back it show like undefined post my code down

const findDocuments = function(db, callback) {
var result
//Call the Collection
const collection = db.collection(dbCollection);
//Find the documents
collection.find({}).toArray(function(err, docs) {
    assert.equal(err, null);
    console.log("Found the following records");
    //console.log(docs);
    callback(docs);
});

}

Find the docuemnts in Database

router.get('/', function(req, res, next) {
//connect to server
MongoClient.connect(url, function(err, client) {
    assert.equal(null, err);
    console.log("Connected correctly to server");
    //call database
    const db = client.db(dbName);
     //find the documents
    findDocuments(db, function(err, callback) {
        console.log("this is the callback: "+ JSON.stringify(callback));
        client.close();
        res.json(callback);
    });
});

});

Add an Image with angular error: Erro from Angular

*** Important error only appear whem i try to send the object back

Thanks for help!

  • You need to setup CORS on your server side – Chau Tran Apr 17 '18 at 17:18
  • You also need to learn that you don't connect to the database on every request. You connect **once** and share the connection instead. See [How do I manage MongoDB connections in a Node.js web application?](https://stackoverflow.com/q/10656574/2313887) as a base reference. Plenty of more material on the subject out there. – Neil Lunn Apr 18 '18 at 02:27
  • Images are useful in a post, but **make sure the post is still clear without them**. Instead of showing a screenshot of your error, copy and paste or type the actual error text into the post directly. cf http://meta.stackoverflow.com/questions/303812/discourage-screenshots-of-code-and-or-errors – Vince Bowdren Apr 18 '18 at 11:49

0 Answers0