The node app's response fails to provide any data, even though it is expected to return

I'm currently running a nodeJS server using the express framework.

When sending a request to the server, it should respond with data in an array format. However, instead of receiving the expected data, I am getting ''.

The specific test I'm attempting to pass is:

it('should send postgres data to the server', function(done) {
  request(app)
  .post('/chart')
  .send({min:"1",max:"100",arrayLength:"12"})
  .expect(200, sqlData)
  .end(function(err, res){
    if(err) {
      done(err);
    } else {
      done();
    }
  });
});

Note that the response should match the value of sqlData being sent back.

Here's what happens when the router receives a POST request:

router.post('/', function(req, res) {
    res.send(randomSqlTableSelector(req.body.min,req.body.max,req.body.arrayLength));
});

I have verified that req.body.min, max, and arrayLength contain the correct values.

The issue likely lies within my function randomSqlTableSelector. Whenever this function is called inside the router, it only returns empty quotes ''.

This is how the function looks like:

function randomSqlTableSelector(min,max,arrayLength) {
    var filledArray = [];
    pg.connect(conString, function(err, client, done) {
        if(err) {
            return console.error('error fetching client from pool', err);
        }
        client.query('SELECT cell1 FROM random AS retrievedNumber;', function(err, result) {
            var psqlData = result.rows;
            for (i in psqlData) {
                filledArray.push(psqlData[i]["cell1"])
            }
            return filledArray
        });
    });
}

Answer №1

When dealing with functions that handle asynchronous and non-blocking tasks, it's important to avoid treating them as if they are synchronous and blocking. Instead, consider using a callback function:

function selectRandomSqlTable(min, max, arrayLength, cb) {
  pg.connect(conString, function(err, client, done) {
    if (err)
      return cb(err);
    client.query('SELECT cell1 FROM random AS retrievedNumber;', function(err, result) {
      if (err)
        return cb(err);
      var psqlData = result.rows,
          filledArray = [],
          i;
      for (i in psqlData)
        filledArray.push(psqlData[i]["cell1"])
      cb(null, filledArray);
    });
  });
}

You can then incorporate this function into your route like so:

router.post('/', function(req, res) {
  var min = req.body.min,
      max = req.body.max,
      len = req.body.arrayLength;
  selectRandomSqlTable(min, max, len, function(err, array) {
    if (err) {
      console.log(err);
      return res.send(500);
    }
    res.send(array);
  });
});

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

Express Generator neglects specified port configuration

Here's the code I'm using to set the port to 3004 in my express generator app, placed right above module.exports = app;: // app.js const PORT = 3004; app.set('port', PORT); app.listen(PORT, () => { console.log(`app listening on ...

There was an error during deployment, as the script for lint was missing

After executing the command below: npm --prefix "$RESOURCE_DIR" run lint An error is displayed as follows: npm ERR! missing script: lint npm ERR! A full log of this operation can be found at: npm ERR! C:\Users\HP\AppData\Roaming&bs ...

Why does npm install a different version of a dependency than what is listed in the package-lock.json file?

node -v v17.2.0 npm -v 8.1.4 package.json { "name": "untitled", "version": "0.0.0", "private": true, "devDependencies": { "stylelint": "^14.1.0" } } npm i ...

Detecting the presence of a session in Angular2 and nodejs using express

My server-side session creation is functioning properly, but I need to be able to hide certain elements in an Angular2 component template depending on whether the session exists. How can I check within my Angular2 component whether the server-created sessi ...

Learn how to utilize the import functionality in Node.js by importing functions from one .js module to another .js module. This process can be seamlessly integrated

Hey there! I'm currently facing a challenge where I need to import a function from one JavaScript file to another. Both files are on the client side in Node.js, so I can't use the require method. If I try to use the import statement, I would need ...

Leveraging promises with node.js and couched/nano for asynchronous operations

Currently experimenting with the Q promises library in conjunction with couchDB and Nano. The code below is able to display messages in the console, however, it seems that the database is not being created as expected. var nano = require('nano') ...

moving passport objects between different routes

Feeling a bit lost in setting up my node application with Express and Passport for authentication. Came across a helpful guide by scott.io that got me started here Everything works fine, but I want to organize my routes better. Planning to have separate r ...

Logging messages in Node.js using console.log while inside an asynchronous function

Can someone explain why the product data isn't appearing when I try to scrape a website using puppeteer? const puppeteer = require("puppeteer"); (async () => { const browser = await puppeteer.launch({ headless: false }); const page = await br ...

Troubleshooting caching problems when deploying a Node.js app on Heroku

Currently, I am facing a challenge while trying to deploy my app on Heroku. Despite being successful in deploying it several times before, I recently updated mongoose from ">= 3.5.0" to ">= 3.6.0rc0" in my packages.json file. The new version 3.6 requires m ...

What is the best way to safely store a logged-in user on the client-side?

As I delve into creating a login system for my simple social media website where users can make posts and view feeds from fellow followers, I've successfully implemented user login. Upon logging in, I'm able to retrieve the user's credential ...

How to extract the parameters separated by slashes from a URL in Next.js

I need some guidance on how to redirect a URL in an express.js configuration. Here's the scenario: The URL is: profile/myname To forward to my page profile.js, I use the following code in my express.js config: server.get('/profile/:username&ap ...

Move massive data between Android and Node.js

I am currently working on an Android photo-taking app developed in React Native that needs to be paired with a React Electron gallery-type app on the user's computer. There is a requirement for transferring a large number of photos directly to the com ...

Retrieve the roster of active users/clients in Socket.io

Looking to retrieve a dynamic list of online users or clients using socket.io for instant messaging. View the image displaying the list of connected users I have successfully implemented a feature to showcase a roster of clients who connect to my route/A ...

Tips for locating the specific website address on a publicly accessible webpage

I am looking to receive notifications whenever a company's public website adds a document to their site. This needs to be done for approximately 400 different public sites. Since each site will have a unique document directory, I plan to create a data ...

A different approach for dynamically displaying React components sourced from an API

As I develop a website using Next.js/React that pulls in content from Strapi CMS, my goal is to create a dynamic page template for news articles. The aim is to empower content editors by giving them the flexibility to choose the type of content they wish t ...

An error occurred when attempting to remove the database file due to it being currently in

I am currently facing an issue with creating and then deleting an SQLite database using the before and after Mocha hooks. When utilizing the Node.js SQLite library, I encounter an 'Error: EBUSY: resource busy or locked...' message upon calling fs ...

Creating a new vertex in AWS Neptune database using JavaScript and Gremlin query language while optionally adding an edge

At times, it may be necessary to create a Vertex with an optional Edge. g.addV('label') .property(id, 'uniq_id_2').as('u') .property('edge_is_needed', edgeIsNeeded) .constant(edgeIsNeeded) .choose(eq(true), addE( ...

Oops! Looks like the file or directory 'E:clientindex.html' cannot be found

Currently, I am attempting to send an HTTP method from an Angular service to trigger an API on Node.js. However, I keep encountering the following error: Error: ENOENT: no such file or directory, stat 'E:\client\index.html' This is th ...

What could be causing replace() to malfunction in Node.js?

I am dealing with some data in Node.js and I am trying to replace the ampersands with their escape key. Below is the code snippet I am using: let newValue = data; for (label in labelData.data) { let key = "Label " + label; newValue = newValue.rep ...

What is the inner workings of stream.Transform in Node.js?

Recently, I stumbled upon a code snippet on a blog showcasing the usage of the stream Transform class to modify data streams and display the altered output. However, there are certain aspects of this code that leave me puzzled. var stream = require(&apos ...