The information returned to the callback function in Angular comes back null

In my Node.js application, I have set up an endpoint like this:

usersRoute.get('/get', function(req, res) {

    //If no date was passed in - just use today's date

    var date = req.query.date || dateFormat(new Date(), 'yyyy-mm-dd'),
        search = req.query.search;

    users.getAllUsers(date, search)
        .then(function(results) {
            res.json(results); 
        }, function(err) {
            res.status(500).json({
                success: false, 
                message: 'Server error.',
                data: []
            });
        });
});

During testing, I mistakenly named my SQL table, causing it to enter the function(err){} block.

The function within my Service is structured as follows:

function getUsers(date, search) {
            return $http.get('/api/users/get', {
                params: {
                    date: UtilsService.formatDate(date),
                    search: search
                }
            })
            .then(getData)
            .catch(handleErr);

            function getData(response) {
                console.log(response);
                return response.data;
            }

            function handleErr(err) {
                console.log(err);
                LoggerService.error('Could not retrieve users.', err ,'Oops');
                return $q.reject(err);
            }
        }

Surprisingly, both console.log statements in the then and catch blocks are returning undefined.

If anyone can shed light on why this is happening, it would be greatly appreciated.

Edit For clarification; Here is more backend code:

Users.js

var sql = require('seriate'); 
var when = require('when');

var getAllUsers = function(date, search) {
     return sql.execute({
        query: sql.fromFile('../sql/users/getAllUsers.sql'),
        params: { 
            date: { 
                type: sql.DATE, 
                val: date 
            },
            search: {
                type: sql.VARCHAR,
                val: search
            }
        }
    });
}

module.exports = {
    getAllUsers: getAllUsers
};

UsersApi.js

var express = require('express');
var dateFormat = require('dateformat');
var users = require('../models/users');
var validation = require('../middleware/validation');

var usersRoute = express.Router();

//Checks for a valid token 
validation.isLoggedIn(usersRoute);

usersRoute.get('/get', function(req, res) {

    //If no date was passed in - just use today's date

    var date = req.query.date || dateFormat(new Date(), 'yyyy-mm-dd'),
        search = req.query.search;

    users.getAllUsers(date, search)
        .then(function(results) {
           res.json(results); 
        }, function(err) {
            res.status(500).json({
                success: false, 
                message: 'Server error.',
                data: []
            });
        });
});

module.exports = usersRoute;

In my service, both the then and catch sections are being executed, with both objects (response and err) turning out to be undefined.

Answer №1

Would you mind sharing the entire service? I have set up a plunker with your code, which is calling a nodejs service hosted on OpenShift. Following the sample you provided, I created a method that simulates your function(err):

self.routes['/get'] = function(req, res) {
    res.status(500).json({
        success: false,
        message: 'Server error.',
        data: []
    });
};

The plunker app looks like this:

var app = angular.module('plunker', []);

app.service('UserService', function($http, $q) {
  this.getUsers = function(date, search) {
    return $http.get('https://nodejs-starters.rhcloud.com/get', {
        params: {
          date: date,
          search: search
        }
      })
      .then(getData)
      .catch(handleErr);
  }

  function getData(response) {
    console.log('status: ' + reponse.status + ' - ' + response.message);
    return response.data;
  }

  function handleErr(err) {
    console.log(JSON.stringify(err));
    console.log('status: ' + err.status + ' Err= ' + err.data.message);
    console.log('Could not retrieve users.', err.data.message, 'Ooops');
    return $q.reject(err);
  }
});

app.controller('MainCtrl', function($scope, $http, $q, UserService) {
  var vm = $scope;
  vm.name = 'World';
  UserService.getUsers(new Date(), '*');

});

The console then displays these results:

app.js:21 {"data":{"success":false,"message":"Server error.","data":[]},"status":500,"config":{"method":"GET","transformRequest":[null],"transformResponse":[null],"params":{"date":"2016-06-02T18:33:50.633Z","search":"*"},"url":"https://nodejs-starters.rhcloud.com/get","headers":{"Accept":"application/json, text/plain, */*"}},"statusText":"Internal Server Error"}
app.js:22 status: 500 Err= Server error.
app.js:23 Could not retrieve users. Server error. Ooops

Therefore, the handleErr function is invoked, and 'err' is defined. As per the nodejs script, 'err.data.success' is false, and 'err.data.message' is 'Server error.'

In the plunker example, would you be able to replace my URL with yours and observe if you receive the same or different result?

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

The bootstrap datepicker does not display the date range on the calendar

I tried to incorporate a bootstrap datepicker date-range in the code snippet below, but I am encountering an issue where the selected date range is not displaying on the calendar. <!DOCTYPE html> <html> <head> <link rel="stylesheet" ...

Exploring the interaction of karma, jasmine, Angular, and UI router through testing the resolve function when using state.go with parameters

In my Angular module "moduleB", I have the state defined as shown below: $stateProvider .state('stateB', { parent: 'stateA', abstract: true, templateUrl : base ...

Encountering a "code redeemed error" when utilizing Google OAuth

Currently, I am working on a project that involves user login through a Google account on localhost. The Google signup functionality has been successfully implemented. However, upon logging in from my account, I encountered the following error message: To ...

The robot will automatically update its own message after a designated period of time

I am facing an issue with my code where the bot is not updating its message after a specific time period defined by time.milliseconds * 1000. How can I make the bot edit its message after that duration? let timeout = 15000; if (author !== null && ...

Indication of a blank tab being displayed

I'm struggling to get my Angular directives working in my project. I've tried implementing a basic one, but for some reason it's not showing anything on the screen. Can anyone help me troubleshoot this issue? Here is my JS code: angular ...

What steps should I take to distribute files for an npm package publication?

I am looking to release an npm package that includes both my source files and distribution files. Within my GitHub repository, I have a src folder containing JavaScript source code. The build process generates a dist folder which holds the distribution fil ...

I'm not skilled in programming, so I'm not sure what the problem is with the code

While working on my Blogger blog, I encountered the need to add a fixed sidebar ad widget that would float along the screen. After trying multiple codes, I finally found one that worked. However, using the template's built-in variable functions led to ...

Cross-Origin Resource Sharing (CORS): The preflight request response does not satisfy the access control check

I've been facing an issue with a simple POST method to my API through the browser. The request fails, but when I try the same on Postman, it works fine. The response includes a JSON string and two cookies. In an attempt to resolve this, I set the hea ...

Using Cookies with Next.js and Vercel

I am facing an issue with my NextJs app deployed on Vercel where the cookie is not being set. Upon checking the console in Network, I can see that the request returns a 200 status and the set-cookie value is present without any warning. However, when I loo ...

Are the sorting algorithms for BackboneJS and AngularJS considered stable sorting methods?

I'm considering incorporating BackboneJS and AngularJS into my app. However, I'm curious about the stability of sorting algorithms in these frameworks. Specifically, I would like to know if they maintain the order of previously sorted columns wit ...

Deploying the app on Heroku and setting up the SSH key for secure

Having trouble pushing code to the Heroku server with this command $ heroku login Enter your Heroku credentials. Email: <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d8b2b9abb3b7bab098b0b7acb5b9b1b4f6bbb7b5">[email pr ...

Transform the componentDidUpdate method that uses prevProps into a custom hook integrated with Redux

Trying to convert a life cycle method into a hook is not working as expected. When the component mounted, if the user ID exists in local storage, the user is connected and their name is displayed in the navbar. If they disconnect and reconnect, their name ...

Avoiding an event from spreading in Angular

I am working on a navigation setup that looks like this: <a (click)="onCustomParameters()"> <app-custom-start-card></app-custom-start-card> </a> When the user clicks on the app-custom-start-card, the onCustomParame ...

Reveal the CSRF token to the client located on a separate domain

Utilizing the module https://www.npmjs.com/package/csurf to safeguard my public routes from cross-site request forgery. Due to the server and client being on separate domains, a direct method of passing the generated token to the client is not feasible. I ...

The Vue/Nuxt application displays content duplication on each page, rendering the content twice without duplicating the components

I recently delved into Vue/Nuxt programming and worked through a tutorial on adding a blog, which I then customized for my website. Everything functions perfectly except that the content is rendering twice. It goes from rendering NavPage (component) > cont ...

What is the best way to declare module variables in a Node.js environment?

When it comes to declaring variables when requiring modules in nodejs, there are different styles followed by well-known developers. For instance, TJ Holowaychuk uses a style like this: (method1) var connect = require('connect') , Router = req ...

Express always correlates the HTTP path with the most recently configured route

Recently, I encountered a strange issue with my Express routes configuration. It seems that no matter which path I request from the server, only the callback for the "/admin" route is being invoked. To shed some light on how routes are set up in my main N ...

Modifying CSS using jQuery in a PHP While Loop

I've been racking my brain trying to solve this issue, experimenting with different approaches but so far, no luck. Question: How can I dynamically change the color of a specific div within a PHP while loop using jQuery after receiving an AJAX respon ...

Is there a recursive method to verify the folder name for each aggregate?

Consider the scenario with these sample documents: (parent_id: null denotes items located at root directory) {"_id":"a", "name":"Pictures", "parent_id": null, "type": "folder"} {"_ ...

The Angular2 Observable fails to be activated by the async pipe

Take a look at this simple code snippet using angular2/rxjs/typescript public rooms: Observable<Room[]>; constructor ( ... ) { this.rooms = this.inspectShipSubject .do(() => console.log('foo')) .switchMap(shi ...