The callback function is not responding properly in my HTTP POST request

I'm currently working with some code that involves callbacks:

function getUserToken(data, callback) {
    var password_sha256 = sha256(data.password);
    getAppById(data.app_id).then(function(res) {
        console.log("app"+res);
            if (!res) {
                console.log("No app");
                callback(err, { meta: {
                    code: 403,
                    error_message: "There are no app with your id!"
                } });
            } else {
                if (res.user_password == password_sha256) {
                    console.log("user found");
                    callback(err, { meta: { code: 200 },
                                    token: password_sha256,
                                    type: 1 });
                    return;
                } else if (res.owner_password == password_sha256) {
                    console.log("owner found");
                    callback(err, { meta: { code: 200 },
                                    token: password_sha256,
                                    type: 0 });
                } else {
                    console.log("user not found");
                    callback(err, { meta: {
                                    code: 403,
                                    error_message: "There are no users with your password!"
                                } });
                }
            }
    });
}

When I use the function above to post some data:

router.post('/api/login', (req, res) => {
    db.getUserToken(req.body, function(err, result) {
        console.log(result);
        if (result.error) {
            return res.status(403).send(result);
        } else {
            return res.status(200).send(result);
        }
    });
});

After executing getUserToken and finding a user, for example, I see "user found" in the console log. However, the callback function in /api/login isn't working as expected. Can you help me identify and fix this error?

Answer №1

Instead of using a callback function, you have the option to return a Promise instead. This can be done with a native Promise implementation or by utilizing an external library such as Kris Kowal Q

var Q = require('q');

function getUserToken(data) {
    var deferred = Q.defer();

    var password_sha256 = sha256(data.password);
    getAppById(data.app_id).then(function(res) {
        if (!res) {
            deferred.reject("There are no apps with your id!");
        } else {
            if (res.user_password == password_sha256) {
                deferred.resolve({
                    token: password_sha256,
                    type: 1
                });
            } else if (res.owner_password == password_sha256) {
                deferred.resolve({
                    token: password_sha256,
                    type: 0
                });
            } else {
                console.log("User not found");
                deferred.reject("There are no users with your password!");
            }
        }
    })
    .catch(function(error) {
        deferred.reject(error);
    });

    return deferred.promise;
}

You can then handle and process the outcome or catch errors when posting data.

router.post('/api/login', (req, res) => {
    db.getUserToken(req.body)
      .then(function(result) {
          res.status(200).send(result);
      })
      .catch(function(error) {
          res.status(403).send(error);
      });
}); 

Answer №2

It is recommended to utilize callback(null, data) instead of callback(err, data) for obtaining the desired results.

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

What is the best way to implement a never-ending scrolling grid loader within a scrollable area using Codeigniter?

In my Codeigniter framework and bootstrap installation, I have multiple sub-pages. On one of these pages, I am attempting to implement an infinite scroll loader using a jQuery script from a tutorial found at gridScrollFx.js. Here is the JS file I am using: ...

Attempting to access an avatar image via an API, only to encounter an error message indicating that the avatar is not defined

userData is a function that retrieves user data from an API using getUserByChainAccount. The username required by getUserByChainAccount is dynamically fetched from buyer. I'm trying to access the avatar, but I keep encountering the error message Unha ...

Show labels for data on a circular graph using angular-chart.js

I recently created a pie chart using angular-chart.js and it's functioning smoothly. However, I'm facing an issue with displaying the data value on each section of the pie chart. My attempt to use Chart.PieceLabel.js by adding the code snippet b ...

Error: When using Express with sqlite3, a TypeError occurs due to the inability

I've been working on displaying data from an sqlite3 database on a web page within my Express application. In my route file, here is what I have: var express = require('express'); var router = express.Router(); var fs = require("fs"); var ...

The functionality to amend, erase, and view a complete listing of users is currently unavailable

Route Information: routes/users.js const express = require('express'); const router = express.Router(); const usersController = require("../controllers/usersController") const auth = require("../utils/auth") router.post(" ...

Optimizing row display for each page with Material UI's pagination feature

I've been attempting to utilize Material UI table pagination to show 5 rows per page, but for some reason it displays all items on the page and doesn't switch between pages. I'm having trouble figuring out where I'm going wrong. To help ...

"JavaScript that doesn't rely on a specific browser

Why does this code behave differently across browsers? What modifications are needed to ensure consistent behavior in all of them? In Firefox, it functions correctly, using the URL /some/path/?searchedText=sometext. However, in IE, nothing happens when cli ...

Encountering a build error with Ubuntu, Node-Gyp, and Canvas – help needed!

Hey there, I'm having some trouble with installing the Canvas package. I've tried Package Versions 6.1.13 and 6.1.3 Here are my system details: Ubuntu 18.04.5, Node 12.18.4 LTS, Python 2.7, g++ installed, pkg-config installed, libjpeg installed ...

The JavaScript file fails to load when accessing port 8080

As I embark on my journey into backend development, please bear with me. Currently, I am working on a JavaScript program that retrieves text data from my localhost. I have set up an HTTP server using Node.js which serves as a regular HTTP server. The serve ...

The error message 'Cannot read property 'navigate' of undefined' is displayed because the function '_this.props.navigation.navigate' is not

I'm facing an issue trying to access 'Home' from Form.js. Despite my efforts in arrowF, routes, and other methods, the same error persists. How can I resolve this? In my Form.js file, when I call onPress=(), I have tried using functions, ...

Determine the necessary adjustment to center the div on the screen and resize it accordingly

Currently, I am in a situation where I must develop a piece of code that will smoothly enlarge a div from nothing to its final dimensions while simultaneously moving it down from the top of the screen. Each time this action is triggered, the final size of ...

The quiet harmony of FeathersJS and Socket.io as they attentively listen to events is

I've been working hard to get everything set up and running smoothly, but it seems like I'm stuck on the last piece of the puzzle. Despite following the documentation closely, I can't seem to figure out what I'm missing. Here is the @an ...

Synchronous loop in Javascript

Is there a method to execute codes asynchronously within a for loop? In this scenario, events ranging from day x to y need to be inserted into the calendar using a for loop. However, the current loop is taking too long, as it has to cover all the days fro ...

I am facing an issue where Postman is not displaying the HTML pages I create in Express

I am facing an issue with linking my HTML page to my express app and trying to view the content through Postman. However, Postman is only displaying a blank page instead of showing my HTML content. Surprisingly, when I test using res.get("this is an exampl ...

Adjust google maps to fill the entire vertical space available

I found this helpful resource for integrating Google Maps into my Ionic app. Everything is working smoothly, but I am trying to make the map fill the remaining height below the header. Currently, I can only set a fixed height in pixels like this: .angula ...

Can someone explain the method for displaying or concealing a menu based on scrolling direction?

https://i.stack.imgur.com/tpDx0.jpg I want to hide this menu when scrolling down and show it when scrolling up. The code for my menu bot is: <script> var previousScroll = 0; $(window).scroll(function(event){ v ...

Prevent the <a> tag href attribute from functioning with jQuery

I came across this code snippet: <script type="text/javascript"> $(document).ready(function() { $("#thang").load("http://www.yahoo.com"); $(".SmoothLink").click( function() { $("#thang").fadeOut(); $("#thang").load( ...

What is the best way to integrate Emotion styled components with TypeScript in a React project?

Currently, I am delving into TypeScript and attempting to convert a small project that utilizes Emotion to TypeScript. I have hit a roadblock at this juncture. The code snippet below export const Title = styled.div(props => ({ fontSize: "20px", ...

Retrieve information from an ajax call within an Angular application

I need assistance with 2 requests I have. $.ajax({ type: "POST", url: "http://sandbox.gasvisor.com:9988/uaa/oauth/token", data: "grant_type=client_credentials", headers: { 'Content-Type': 'application/x-www-form-urlencoded&a ...

Oops! Looks like there was an issue with defining Angular in AngularJS

I am encountering issues while attempting to launch my Angular application. When using npm install, I encountered the following error: ReferenceError: angular is not defined at Object.<anonymous> (C:\Users\GrupoBECM18\Documents&bs ...