Why I'm always getting an Internal Server Error (code 500) after making a request to BackEnd

Viewed 25

I'm having a little trouble with my site and I can't understand what is happening. First of all I have to say that I was NOT having this behavior when developing on localhost, but now that my site is close to be completed I think that uploading my code to a hosting service and make some tests there would be a good idea.

The issue is that when I make a request to the database, most of the times the site keeps in an eternal loading state, until the error code 500: Internal Server Error appears (I said "most of the times" because it works nice sometime, but normally it remains in a pending state).

Given the fact that SOME TIMES the request work nice, makes me think that the issue is not on the server.js file (where I defined the endpoints), and also is not on my controllers files (where I have some logic and the requests itself).

I'll leave here some pics as example of what is happening but if you need some extra info just tell me:

A simple login example, I just fill the fields and send the request Step one: Login and send request

And here you can see how the request remain as pending enter image description here enter image description here

Until it fails enter image description here

EDIT: I'm using package Mysql2 to connect to the DB, and I was reading that this behavior may be because a bad use of connections (and I'm reading about "pools", but I'm kinda lost tbh)

Here is the connection file:

require("dotenv").config();
const mysql = require("mysql2");

const db = mysql.createConnection({
    host: process.env.DB_HOST,
    user: process.env.DB_USER,
    password: process.env.DB_PASSWORD,
    database: process.env.DB_NAME,
    waitForConnections: true,
});

const connection = async () => {
    db.connect((err) => {
        if (err) throw err;
        console.log("Successfully connected");
    })
}

exports.db = db;
exports.connection = connection;

The first call to the DB (just to check the connection)

connection().then(() => {
    app.listen(port, () => {
        console.log(`Server running at ...`);
    });
});

And the login logic

app.post("/dev-end/api/login", async (req, res) => {
     await singleAccount(db, req.body.email)
        .then(async (response) => {
            if (response.code) {
                res.render("templateLogin");
             }
            try {
                if (await bcrypt.compare(req.body.password, response.password)) {
                    const user = { id: response._id, name: response.name };
                    await deleteTokenById(db, user.id.toString());
                    const accessToken = generateAccessToken(user);
                    const refreshToken = jwt.sign(
                        user,
                        process.env.REFRESH_TOKEN_SECRET,
                        { expiresIn: "604800s" }
                    );
                    createToken(db, {
                        _id: user.id,
                        accessToken: accessToken,
                        refreshToken: refreshToken,
                        createdAt: new Date().toISOString().slice(0, 19).replace("T", " "),
                    }).then(
                        res
                            .cookie("access_token", accessToken, {
                                httpOnly: true,
                                maxAge: 60000 * 60 * 24 * 7,
                            })
                            .redirect("/dev-end/dashboard")
                    );
                } else {
                    res.render("templateLogin");
                }
            } catch {
                res.status(500).send();
            }
        })
        .catch(console.log);
});

=>=>=>=>=>=>=>=>=>=>=>=>=>=>=>=>

const singleAccount = async (conn, email) => {
    return await read(conn).then((res) => {
        if (!res.code) {
            const result = res.find((e) => e.email.toString() === email);
            if (!result) {
                return {
                    code: 404,
                    msg: "No account was found with the provided id",
                };
            }
            return result;
        }
        return res;
    });
};

=>=>=>=>=>=>=>=>=>=>=>=>=>=>=>=>

const read = async (conn) => {
    const sql = `SELECT * FROM accounts`;
    return await conn.promise().query(sql)
        .then(([res, fields]) => res);
};
0 Answers
Related