The Ajax query returned a successful response, yet it unexpectedly triggered an error

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.

Answer №1

When it comes to client-side operations, using JSONP is the best option available. To make a proper Ajax JSON call to the server, you'll need to enable CORS on your localhost.

If you're not sure how to do this, check out these helpful tutorials: Deadly CORS when http://localhost is the origin

You can also search for instructions by Googling "Enable CORS on localhost."

We hope this information proves useful to you!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Pagination in Mongoose implemented on the server side

I am currently working on implementing server side pagination in a NodeJS, Express, and MongoDB API. The API relies on mongoose to interact with the database. I am struggling with customizing the response from the Controller. Model: const mongoose = requ ...

Prevent a submit button from submitting a form using jQuery

I am working on developing a password manager similar to a chrome extension. The goal is to detect the username and password fields when a user tries to log in to a website, such as Facebook, and then prompt the user if they would like to save these creden ...

Collecting code coverage with Istanbul while testing HTTP endpoints using tools like Postman or Karate: A comprehensive guide

I'm currently working on a JavaScript project that utilizes Express to create various endpoints using the typical express/router pattern. const express = require('express'); const router = new express.Router(); router.post('/', a ...

Having trouble connecting to the MongoDB Replicaset pods from other pods, receiving the error message: "unable to access 10.1.231.87:27017 | connect

I have successfully set up a MongoDB statefulset in a microk8s Kubernetes cluster. To connect to the PRIMARY replica, I use the pod's IP address in my host's terminal with the following command: mongosh "mongodb://10.1.231.87:27017/test". In thi ...

Tips for integrating PHP into a Bootstrap modal dialog

After discovering and modifying a php script designed to process contact form content and display alerts on a Bootstrap 3 modal window, I encountered some issues. While I was able to successfully display errors and show the modal onload without any php con ...

How to Query MongoDB and reference an object's properties

I'm trying to execute a script on my MongoDB that will set teacher_ids[] = [document.owner_id]. The field owner_id already exists in all the objects in the collection. Here is my current attempt: db.getCollection('readings').update({ $where ...

String Representation of Mongoose Date Retrieval

Mongoose Model: const patientSchema = new mongoose.Schema({ firstName: String, middleName: String, lastName: String, addresses: [addressSubschema], dateOfBirth: Date, files: [{ type: mongoose.Schema.Types.ObjectId, ref: 'File&a ...

Trouble with displaying an array of React elements in the render() function

While learning React by creating sample projects with Meteor, I've managed to grasp the basics but hit a wall. I'm utilizing a Twitter API to fetch the latest three tweets from the BOINGBOING Twitter page. The API is functional, and I can succes ...

Identical Identifiers in jQuery Tab Elements

Currently, I am utilizing the jQuery Tabs library within a small application. Within this page, there are 5 tabs that load content using Ajax. However, an issue arises when a tab is loaded and remains in the browser's memory along with its HTML elemen ...

What steps can be taken to ensure a function operates even when the mouse is stationary?

$(document).ready(function() { var score = 0; $("body").mousemove(function() { score++; $("#result").val(score); console.log(score); }); }); As I move my mouse, the score keeps increasing. But, I'm wonde ...

Hide multiple divs with similar ids in JQuery when clicking outside of them

Is there a way to hide all div elements with similar id if none of them are clicked on? Currently, my code only works for the first div because I am using index[0] to retrieve the id. How can I make it work for all ids? Below is the code snippet: $(win ...

Can Angular 4 experience race conditions?

Here is a snippet of my Angular 4 Service code: @Injectable() export class MyService { private myArray: string[] = []; constructor() { } private calculate(result): void { myArray.length = 0; // Perform calculations and add results to myAr ...

What is the best way to incorporate a dynamic background in NextJS using Tailwind?

I have a poster image that I want to use as a background image, fetched from MovieDb. I tried putting it inside the className like this: className={bg-[url('${path}')] h-screen bg-cover bg-center text-white border-b-8 border-b-solid border-b-sla ...

Reduce the identification number within a JSON array following the removal of an item

Within my local storage, I maintain a dynamic array. Each entry is accompanied by an ID that increments sequentially. If a user opts to delete an entry, it should be removed from the array while ensuring that the IDs remain in ascending order. For example: ...

Sending information from one function to another in NodeJS using the MSSQL driver

Currently working with an SQL Server in NodeJS, and successfully pulling data. However, struggling to pass the retrieved data back to the calling function. Below is my code snippet for querying the database: const dbq = require('./dbquery.js'); ...

Attempting to insert a square-shaped div within a larger square-shaped div and enable it to be moved around by dragging

Imagine this scenario: I have a button and a large div. When the button is clicked, the code adds a new div inside the larger one. However, the new div is not draggable because I didn't implement the necessary code. I'm also trying to figure out ...

ReactAppI am facing an issue where the browser fails to refresh the page upon saving changes in my JavaScript file using the VS code editor

Can anyone remind me of the tool we can install to refresh the browser page automatically whenever we save changes in our editor? ...

How can I prevent my Vue.js application from losing focus when navigating to different components?

I am encountering an issue with my Vue.js app where the focus is lost when changing routes. Initially, when the site loads, the first element of the header component is correctly in focus as desired. However, when navigating to a different link on the site ...

Developing an Addon for Firefox using XUL and JavaScript

I am interested in creating a Firefox Addon that dynamically generates a button in the webpage's DOM when a specific page like www.google.com is loaded. This button, when clicked, will redirect to another page such as www.stackoverflow.com. It is imp ...

Avoid Updating State After Adding Row in material-table

When utilizing the material-table library, my goal is to display a different component upon adding a row. Although the code functions as expected, I encountered the following error in the console: Warning: Can't perform a React state update on an unm ...