Tips for generating numerous queries within one GET request

Can I use node-pg to execute multiple queries in a single GET request?

For instance, if I have code that looks like this:

const getSomeInfo = (request, response) => {
    
    pool.query('SELECT * FROM jobs', (error, results) => {
        if (error) {
            throw error
        }
        var jobObj = results.rows;
        response.render('pages/jobinfo', {
            jobObj: jobObj
        });
    })

    pool.query('SELECT * FROM description INNER JOIN views', (error, results) => {
        if (error) {
            throw error
        }
        var descObj = results.rows;
        response.render('pages/jobinfo', {
            descObj: descObj
        });
    })
    
}

However, when running this code, I encounter the error

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
.

Is there a way to successfully run both these queries in one GET request so that the data is accessible on the same page?

Answer №1

Rendering only one document is possible, and that document can contain two local variables originating from separate queries. To execute the queries concurrently, consider using the Promise.all method along with noting that pool.query without a callback function returns a promise.

const fetchSomeInfo = (request, response) => {
    
  Promise.all([
    pool.query('SELECT * FROM jobs'),
    pool.query('SELECT * FROM description INNER JOIN views')
  ]).then(function([jobData, descData]) {
    response.render('pages/jobinfo', {
      jobObject: jobData.rows,
      descObject: descData.rows
    });
  }, function(error) {
    throw error;
  });
    
}

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

Error 400 occurs when using mutation, yet the same mutation successfully executes in GraphiQL

After following tutorials and attempting to learn GraphQL with React and Express, I've hit a roadblock. The mutation works fine when I test it in graphiql but fails when called from my client. Client Code: async addBook(params) { var title = par ...

What could be the reason for Express indicating that the default view engine has not been defined?

Currently, I am developing an application using Node.js and MongoDB for the backend. Express is being used to test the app, and I am attempting to utilize EJS for rendering my HTML files. However, I am encountering a problem where my default view engine is ...

Using Node Express to fill out forms with AJAX

Is it possible to update a specific section of a webpage using AJAX without having to refresh the entire page? If so, how can this be achieved correctly? //Get Book router.get('/form/:id', (req, res) => { Book.findOne({ _id: req.params ...

Resource loading error: The server returned a 404 (Not Found) status code, as shown in the console

Click here I have a simple file structure where index.html, script.js, and login.js are all in the same root folder without any subfolders. The issue I'm facing is that although the connection to the database works fine, there seems to be a problem wi ...

Error: The function register.route(...) does not support the use method

Upon using express.Router(), I encounter an error when attempting to apply the use method, resulting in the following message: TypeError: register.route(...).use is not a function Code /server/routes const express = require('express'); const re ...

Choose Status Menu DiscordJS version 14

Is there a way to get help with changing the bot's status if it's not working properly? The value of the variable "statuses" is set as status, but the status itself does not change. Using client.user.setStatus('dnd'); can sometimes work ...

In what format is the parameter accepted by the .getDay() method?

Here's the plan: I need to extract information from an input element with type set as date. This data will then be stored in a .json file and later parsed when the program is initiated. Subsequently, I aim to utilize the date.getDay() function to dete ...

Is there a way to verify user credentials on the server using FeathersJS?

Currently, my single-page app is utilizing feathers client auth and a local strategy for authentication. I have implemented various middleware routes and I am looking to verify if the user is authenticated. If not, I would like to redirect them to /. Bel ...

What is the best way to incorporate real-time push notifications on my website?

My website consists of two main parts. One part is utilized by individuals labeled as X, while the other is reserved for those identified as Y. When a person from group X requests assistance, members of group Y promptly respond with an estimated time of ...

Error encountered: No geographic indices found for executing a geoNear operation with Mongoose

Initially, I had divided the schemas but later nested them inside my overall document. Despite adding indexes and removing coordinates from location, there seems to be an issue with the nested points. Upon running get Indexes, it shows that there is an i ...

Tips for deploying an Angular Universal 9 application on a live server

Our Angular 9 app functions perfectly when deployed on an IIS server. We also have a version of the app that has been integrated with Universal by another company. Now, we need to figure out how to deploy our app with server-side rendering into productio ...

The download functionality in HTML5 is not functioning properly, so users are forced to rename files when downloading

For weeks, I've been struggling to change the name of the downloaded file. Despite my efforts, instead of being named Chrysanthemum.jpg, it ends up as a hash of the file like 241693260.jpg In my backend setup, I utilize Node.js and Express.js for man ...

Updates to Mongoose validators have not been implemented

I am currently using the mongoose library along with the npm package called "mongoose-unique-validator" to handle validation in my application. Initially, I had no issues integrating it into my schema and it worked perfectly fine. However, I recently made ...

I'm currently attempting to establish a connection between my server.js express API and MongoDB, but I keep encountering an unfamiliar error message that I'm having trouble decipher

Here is the server.js code: import express from 'express'; import bodyParser from 'body-parser'; import userRoutes from './routes/users.js'; import mongoose from 'mongoose'; co ...

Ways to deduce or implement intellisense for parameter types in overloaded functions

Currently, I am developing an Electron application where numerous events are being passed around with specific listeners assigned to each event. One example is BrowserWindow.on: Electron.BrowserWindow.on(event, listener) The event can take on values such ...

How to resolve the Angular SSR authentication guard issue to briefly display the login page upon refreshing?

I have a love-hate relationship with auth.guard.ts: import { Injectable } from '@angular/core'; import { CanActivateChild, Router } from '@angular/router'; import { Observable, of } from 'rxjs'; import { AuthService } from &a ...

How come we have located the executable file?

After running the command npm install grunt -g, a folder is created at C:\Users\myname\AppData\Roaming\npm\node_modules\grunt-cli. However, in my path variable, only the C:\Users\myname\AppData\Roaming ...

Error: The property 'case sensitive routing' cannot be accessed because it is undefined

Task at hand: Running ExpressJS port using Node.js, nodemon, and lib. Operating System: Windows 10 Home x64 Node.JS Version: Lts The Challenge: Getting the ExpressJS port to run successfully. Current Issue: Encountering an internal file error, potentiall ...

teasing es6 imports in unit testing

Imagine a scenario where we have a file named source.js that needs to be tested: // source.js import x from './x'; export default () => x(); The unit test code for this file is quite simple: // test.js import test from 'ava'; imp ...

Making an HTTP redirect request in a NodeJS environment

I am in the process of developing a basic NodeJs Server. Whenever this server receives a request, it performs certain actions in the background and then redirects the user to another webpage. This is the code snippet I am working with: const http = require ...