The HTTP GET request is failing to trigger

I'm currently working on building a basic messageboard using MongoDB, Angular, NODE.js and Express.

Oddly enough, everything works fine the first time I call getMessages(). But when I try to call getMessages() after posting a message with postMessage(), no GET request is being sent.

Below are my defined routes:

app.get('/api/message', function(req, res) {
    Message.find({}).exec(function(err, result) {
        res.send(result);
    });
});

app.post('/api/message', function(req, res) {
    console.log(req.body);

     var message = new Message(req.body);
     message.save();

     res.status(200).send('Message added');
})

This is the code snippet for my angular controller:

(function() {
'use strict';

angular
    .module('app')
    .controller('MainController', mainController);

function mainController(navigationFactory, $http, $timeout, apiFactory, $scope) {

    var that = this; // jshint ignore: line

    function init() {
        that.getMessages();
    }

    that.postMessage = function() {

        apiFactory.postMessage(that.message).then(function() {
            console.log('Posted from controller'); 
            that.getMessages(); 
        });

    }

    that.getMessages = function() {
        console.log('Getting from controller');
        $http.get('http://localhost:5000/api/message').then(function(result) {
                console.log(result.data); 
                that.messages = result.data;
               console.log('Set data'); 
        });   
    }

     init();

}
})();

Additionally, I use a factory method to handle posting the message:

factory.postMessage = function(message) {
        return $http.post('http://localhost:5000/api/message', {msg: message});       
 }

Although I have tried debugging and checking several times, I am unable to figure out why there is no HTTP GET Request happening even though getMessages() is called within my postMessage() function. The console logs indicate that getMessages() is indeed triggered, but it appears to finish executing before sending any request.

Answer №1

It seems like the problem lies in the server side promise. You can try implementing the following code snippet:

app.get('/api/message', function(req, res) {
    return Message.find({}).exec(function(err, result) {
        if(err) {
          return res.status(500).send(err);
        }
        return res.status(200).json(result);
    });
});

Answer №2

It appears that there may be a hoisting issue causing the function to be called before it is declared. Have you tried rearranging the order of your code like this?

var that = this; // jshint ignore: line

that.getMessages = function() {
    console.log('Retrieving from controller'); //gets logged
    $http.get('http://localhost:5000/api/message').then(function(result) {
            console.log(result.data); //Logs old result, without new message
            that.messages = result.data;
           console.log('Data has been set'); //gets logged
    });   
}

that.postMessage = function() {

    apiFactory.postMessage(that.message).then(function() {
        console.log('Posted from controller'); //gets logged
        that.getMessages(); 
    });
    //that.getMessages(); <-- also tried this

}

function init() {
    that.getMessages();
}

init();

Comparing var functionName = function() {} and function functionName() {} syntax

UPDATE:

I have made adjustments in your Plunker and now everything seems to be functioning correctly!

The main issue was due to the missing injection of $http into your controller... This prevented your GET request from being executed

Working version on Plunker

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

Steps for integrating HLS video service with Vue3.js single page application

As I work on developing a video streaming platform using Vue.js, one particular challenge has come to my attention. When utilizing single-page application (SPA) frameworks like Vue.js, JavaScript code runs on the client's browser. This means that segm ...

Do not save cookies when users visit public pages

Utilizing NodeJS along with express-session, I have implemented a method to store session data in the database, as per recommendations from Log user out of previous sessions. The main script contains the relevant code: const session = require('express ...

Sort Ionic Expandable List

Currently, I am in the process of creating an application using Ionic framework. One feature in my app involves displaying a list with professions and their corresponding specialties in an accordion format, as demonstrated below: Profession 1 Specialty ...

Ensure that the script continues to run uninterrupted even after the user has navigated away from the

Currently, I am working on an application that allows users to purchase tickets for events using technologies such as node.js, express.js, sequelize, and react. After the user completes the ticket purchasing process, they are redirected to a page indicati ...

The websocket connection in npm automatically closes after a certain period of time

I am using the ws package from npm in my node.js project for socket programming. Here is the code snippet: var server = require('ws').Server; var serverConnection = new server({port : 5000}); serverConnection.on('connection',functio ...

Transform an item into a map of the item's properties

I am faced with an object containing unknown key/value pairs in this format: myObj = { key_1: value_1, key_2: value_2, key_n: value_n } My goal is to transform it into a dictionary of structured objects like the one below: dictOfStructureObjec ...

Sort a JSON array alphabetically in Angular.js even when there are no key/value pairs specified

I'm having trouble alphabetizing a list using a JSON array in my code. Despite my efforts, the sorting doesn't seem to be working correctly. You can view my current code by following this link to the jsfiddle http://jsfiddle.net/hxxLaxL3/ Here i ...

Leveraging NodeJs Environment Variables within ViteJS React Components

When using ViteJs to build a ReactJs Project, the vite.config.ts file contains the following: const isDev = process.env["DFX_NETWORK"] !== "ic" const network = process.env.DFX_NETWORK || (process.env.NODE_ENV === "production&quo ...

When making an axios post request and using node pdfkit, the generated PDF appears blank

I encountered an issue while using react with axios to send a post request to the express server for creating a PDF using pdfkit. Even though the file is automatically downloaded upon receiving, the content of the PDF appears to be blank when opened. impor ...

Origin Access-Control-Allow Not Recognized

Currently, I am developing a node.js app and have encountered a strange issue: This particular Angularjs snippet... // delete hosts $scope.delete = function(row) { var rowData = { hostname: row.hostname, ipaddr: row.ipAddress, ...

The callback function in JavaScript seems to be missing without ever being executed

I have a SendMail function using nodemailer that successfully sends emails, but the callback function logging "mail sent" is not getting executed. Any suggestions on what might be causing this? var email = '<a href="/cdn-cgi/l/email-protection" cla ...

An effective way to capture ng-model along with ng-bind

I'm having trouble getting the ng-bind="data1" to display the selected date from the widget when it is clicked on and a date is chosen. The ng-bind does not seem to be capturing the chosen date properly. <!DOCTYPE HTML> <html> <head> ...

Issue: rootScope:infdig has detected that the maximum number of $digest() iterations (10) has been reached

I've developed a custom directive that utilizes certain scope parameters. To monitor changes in these incoming parameters, I have implemented a watchGroup within the directive: scope.$watchGroup(['repairer', 'initial&apos ...

Extracting all usernames of members present in a specific voice channel and converting them into a string using Node.js on Discord

Hey everyone, I'm looking for a code snippet that will help me retrieve all the members from a specific voice channel by using its ID. I also need to extract and store the usernames of these members who are currently in that particular voice channel w ...

Is there a harmonious relationship between next.js and mongodb?

I searched extensively for a solution to my issue but still haven't found a clear answer. When working with MongoDB, it's common practice to establish a connection and then close it after completing the task. However, in environments like next.js ...

Having trouble with PHP's JSON encoding functionality?

Take a look at my code for validating with angular and php. I need to check the validity of this form <form ng-submit="dk()"> <label for="">Name</label> <input type="text" name="name" ng-model="formData.name"> {{errorName}} &l ...

The JSON data structure is not being maintained

I am facing an issue with updating the json object model values using the code below. Even after changing the values, it seems like the model is not getting updated. I tried removing the async code and that worked. Why does the async code not work in this ...

Is it necessary to define module.exports when using require() to import a file?

While setting up my Express server, I am using Babel to transpile my ES6 files seamlessly. In my vanilla JS server.js file, I include require('babel-core/register') and require('./app'). Within my ES6 file app.js, I handle all the usua ...

Is it possible to easily remove the trailing comma, period, or other punctuation from the end when using the JavaScript pug template engine?

Apologies for the confusion in my question wording. To illustrate, here is an example piece of code: p #[strong Genre]&nbsp; each val in book.genre a(href = val.url) #{val.name} | , I am trying to figure out how to format a comma ...

Azure deployment encountering unsupported platform error for fsEvents in Npm

Whenever I try to run npm install, I encounter the following error message: npm ERR! code EBADPLATFORM npm ERR! notsup Unsupported platform for <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7b1d081e0d1e150f083b4a5548457805040 ...