Express serverless-http error decoding lambda response: invalid status code returned from lambda: 0

My website name is https://bellumserver.netlify.app, and I’m building an API inside it.

When I do the function for it to manage a post request, it returns the error error decoding lambda response: invalid status code returned from lambda: 0

This is my code:

const express = require('express');
const serverless = require('serverless-http');
const mysql = require('mysql')
const app = express();
const router = express.Router();
const cors = require('cors')

app.use(cors())
app.use(express.json())

router.get('/', (req, res) => { //la app funciona
	res.send('App is corriendo...');
});

const db = mysql.createPool({ //crear la conexion a la base de datos
	host: '---',
	user: '---',
	password: '---',
	database: '---'
})

router.post("/actualizarrango", (req, res) => {
	const idCuenta = req.body.idCuenta
	const division = req.body.division
	const rango = req.body.rango
	const lps = req.body.lps
	const fecha = req.body.fecha

	const sqlInsert = "INSERT INTO `historial` (`id_cuenta`, `division`, `rango`, `lps`, `fecha`) VALUES (?, ?, ?, ?, ?)"
	console.log(sqlInsert)
	console.log(req.body)
	db.query(sqlInsert, [idCuenta, division, rango, lps, fecha], (err, result) => {
		console.log(result)
		res.status(200)
		db.end()
	})
})

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

If I have to guess, db.query() would most likely be an async call. You should try using:

router.post("/actualizarrango", (req, res) => {
  db.query().then(() => {
    res.status(200)
  })
}

Using async/await and Promises is recommended than relying on callback functions in Lambda.

1 Like

Hello there, thanks for the answer. I got it running perfectly with a single line in the function.

	const idCuenta = req.body.idCuenta
	const division = req.body.division
	const rango = req.body.rango
	const lps = req.body.lps
	const fecha = req.body.fecha

	const sqlInsert = "INSERT INTO `historial` (`id_cuenta`, `division`, `rango`, `lps`, `fecha`) VALUES (?, ?, ?, ?, ?)"
	db.query(sqlInsert, [idCuenta, division, rango, lps, fecha], (err, result) => {
		res.status(200)
		res.end("Successfully inserted - 200")
	})
})

As you can see it is almost the same but inside the arrow function I also add res.end("Successfully inserted - 200"). For some reason this makes it work perfectly