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
Not sure what could have been causing the issue, but I created a new
db.js
file in/server
(as opposed to usingconst pool = require(__dirname + "/config/db.config.js");
Within that file is the following:I updated
/server/index.js
to:Now, sending
GET http://localhost:3001/users/1
via Postman returns the row whereuser_id = 1
You’re missing a
return
:Without this, when you get an error, it will try to call
next
first, then try to sendres.status(200)
, then fail with an exception when accessing.rows
onusers
. 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.