Currently, I am delving into the realm of mongodb. I have integrated Express, Body-Parser, and Mongoose into my project, and I'm retrieving data from an online mongodb database hosted on mlab. Everything seems to be functioning smoothly as I've tested Get, Post, and Delete functionalities using Postman. My aim now is to fetch this data using JavaScript in order to display it in HTML format. For this purpose, I am employing Ajax which, although successful, seems to trigger the fail function.
The mongdb controller snippet:
exports.photoalbum_all = function (req, res, next) {
PhotoAlbum.find(({}), function (err, photoalbum) {
if (err) return next(err);
res.send("../Views/images", {photo: photoalbum});
});};
The Ajax call being made:
function getPhoto() {
var photoAdd = 'http://localhost:1234/photoalbums/find';
$.ajax({
header: 'Access-Control-Allow-Origin: *',
dataType: "jsonp",
url: photoAdd,
contentType: 'application/json; charset=utf-8',
async: false,
crossDomain: true,
success: AjaxSucceeded,
error: AjaxFailed
});
}
function AjaxSucceeded(result) {
alert("hello");
alert(result);
}
function AjaxFailed(result) {
debugger;
alert("hello1");
alert(result.statusText);
}
getPhoto();
Initially, I encountered errors related to ajax cross-origin request blocked, hence I had to utilize datatype: 'jsonp'. Upon inspecting the network log in the Chrome browser console, I noticed a successful response with the following address:
http://localhost:1234/photoalbums/find?callback=jQuery111202567313069615542_1545928466705&_=1545928466706
This URL returned the Json values below:
[{"_id":"5c22a5ffcb29611f905f756b","title":"prayer","albums":[{"_id":"5c22a5ffcb29611f905f756c","u_name":"family01","u_title":"family_man"}],"createdAt":"2018-12-25T21:49:51.091Z","updatedAt":"2018-12-25T21:49:51.091Z","__v":0},{"_id":"5c22a66bd3527c39342fafe7","title":"prayer","albums":[{"_id":"5c22a66bd3527c39342fafe8","u_name":"family01","u_title":"family_man"}],"createdAt":"2018-12-25T21:51:39.274Z","updatedAt":"2018-12-25T21:51:39.274Z","__v":0}]
Despite exhaustive research efforts, I haven't been able to pinpoint the issue. The formatting of the Json response received from mlab is a suspicion though. Any insights or suggestions are welcomed. Thank you in advance for your assistance.