Mysql query returns 502 error for lambda function

Whenever I try to execute a mysql db query I am getting a “Failed to load resource: the server responded with a status of 502 ()” error on my draft deploy website here.

I have an express server set up as my single lambda function and it works fine if I uncomment the commented code below and remove the mysql db query call.

const express = require("express");
const bodyParser = require("body-parser");
const serverless = require('serverless-http');
const mysql = require("mysql");
const db = mysql.createConnection({ .... });

const app = express();
const router = express.Router();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

router.get("/api/getSalesData", async (req, res) => {
    // res.send({ express: "Hello from express" });
    db.query("SELECT * FROM Sales", (err, rows) => {
        if (err) throw err;
        res.send(rows);
    });
});

app.use('/.netlify/functions/server', router);
module.exports = app;
module.exports.handler = serverless(app);

Is there any easy workaround to this or something that I am missing?

Hi,

Is there a reason you’re using express? You don’t need it to accomplish what you’re doing in this function. However, it shouldn’t be preventing your query from working.

Have you tried adding logging for the error that you’re throwing? it doesn’t look like you’re catching it anywhere, or doing anything with it. If the query is throwing then the error might tell you what you need to do to fix it.

Can I just do this to get the error back?

if (err) res.send({ error: err });

I was trying to add logger info but since this is all on the server there’s no way for me to do that right? I’ve tried to check my netlify functions log on netlify but that’s never catching anything.

And the reason I’m using express is because this it’s what I’m used to and I have more api endpoints that I wanted to all be in one file. All of the examples I saw online looked like I would have to create separate functions for each api endpoint in a specific format / file. The express way looked better to me for development / deployment.

When I change the method to

db.connect(function(err) {
        if (err) res.send({ error: err });
        db.query("SELECT * FROM Sales LIMIT 5",(err, rows) => {
            if (err) res.send({ error: err });
            res.send(rows);
        });

        db.end();
    });

I still am not getting the actual error.

I get an error message back that looks like this

{errorMessage: "RequestId: d19b6ad3-9304-4d34-8027-1f98e829e3f5 Process exited before completing request"}

Not super awesome to start multiple threads on the same topic, @rmbh4211995 at least not without linking from one to the other. Could you help us out with that in the future so we don’t try to answer one question more than once? Thanks in advance!

Check out my other reply about what I think is happening to your execution