skip to Main Content

Trying to make a GET call from the front end to select the username in the row where user_id = 1 by using parameterized queries. Hard-coded queries work fine, but parameterized queries cause the request to be aborted and returns the following error in dev-tools console:

message: "Request aborted", name: "AxiosError", code: "ECONNABORTED", config: {…}, request: XMLHttpRequest }

EDIT: I’ve edited my code to try and narrow down the issue.
EDIT 2: edited again, may have been out of sync

/server/index.js

require("dotenv").config({ path: __dirname + "/.env" });
const express = require('express');
const pool = require(__dirname + "/config/db.config.js");   // *
 
const app = express();
 
const PORT = process.env.PORT || 3001;
 
const getUsers =  (req, res, next) => {  
  let userID = Number(req.query.user_id);
  pool.query('SELECT * FROM users WHERE user_id = 1', (error, users) => {
    if (error) {
      next(error)
    }
    res.status(200).json(users.rows)
    console.log(userID)
  })
}
 
app.get('/users', getUsers)

app.get("/", (req, res) => {
  res.send("Hello World!");
});
 
app.listen(PORT, () => {
    console.log(
    `# Server started on port: ${PORT}`);
})

The issue is that when I try using parameterized queries, the requests fail. The hardcoded user_id = 1 above works, and outputs the correct row. But the following fails:

const getUsers =  (req, res, next) => {  
  let userID = Number(req.query.user_id);
  pool.query('SELECT * FROM users WHERE user_id = $1', [userID], (error, users) => {
    if (error) {
      next(error)
    }
    res.status(200).json(users.rows)
    console.log(userID)
  })
}

When I GET http://localhost:3001/users?user_id=1 with those changes, Postman just shows "Sending request…" endlessly. Whereas with the hardcoded user_id = 1, Postman returns the correct row and server console shows "1" at every GET request.

2

Answers


  1. Chosen as BEST ANSWER

    Not sure what could have been causing the issue, but I created a new db.js file in /server (as opposed to using const pool = require(__dirname + "/config/db.config.js"); Within that file is the following:

    const { Pool } = require('pg');
    
    const pool = new Pool({
      user: '[USERNAME]',
      host: '[HOST_IP]',
      database: '[DB_NAME]',
      password: '[PASSWORD]',
      port: 5432, 
    });
    
    module.exports = pool;
    

    I updated /server/index.js to:

    // /server/index.js
    const express = require('express');
    const pool = require('./db'); // Path to your db.js file
    
    const app = express();
    
    app.get('/users/:user_id', async (req, res) => {
      const userID = req.params.user_id;
      
      try {
        const query = 'SELECT * FROM users WHERE user_id = $1';
        const result = await pool.query(query, [userID]);
    
        res.json(result.rows);
      } catch (error) {
        console.error('Error executing query:', error);
        res.status(500).json({ error: 'Internal Server Error' });
      }
    });
    
    const PORT = process.env.PORT || 3001;
    app.listen(PORT, () => {
      console.log(`Server running on port ${PORT}`);
    });
    

    Now, sending GET http://localhost:3001/users/1 via Postman returns the row where user_id = 1


  2. You’re missing a return:

    const getUsers =  (req, res, next) => {  
      let userID = Number(req.query.user_id);
      pool.query('SELECT * FROM users WHERE user_id = $1', [userID], (error, users) => {
        if (error) {
          return next(error)
    //    ^^^^^^
        }
        res.status(200).json(users.rows)
        console.log(userID)
      })
    }
    

    Without this, when you get an error, it will try to call next first, then try to send res.status(200), then fail with an exception when accessing .rows on users. This may crash the server or at least seems to make express abort the response that would be sent by the default error handler.

    Your solution that converts the code to use promises (with async/await) is much better, as it avoids such pitfalls with error handling. Now just make sure to use express.js v5 which does natively handle rejections of promises returned by middlewares.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search