I have a backend in lambda connected to a mongodb database. When I test in API Gateway, trying to get api/products, a route setup in my lambda, I get the 502: Malformed Lambda proxy response error. I added a console.log to see what the response output is and this is what I was returned, as found in the CloudWatch logs:
2024-05-07T22:13:57.899Z 2ae75cd7-d8ad-42d3-b83b-429612595df2 INFO Handler response: {
statusCode: 200,
headers: {
'x-powered-by': 'Express',
'content-type': 'application/json; charset=utf-8',
'content-length': '1430',
etag: 'W/"596-51kWiVXfczmv6qVwZ+CxKCL2CKA"'
},
isBase64Encoded: false,
body: '{"products":[{"_id":"4","user":"6","name":"Mason","image":"/uploads/image-4.jpg","brand":"Danza","Category":"Trousers","ageGroup":"Adult","syllabus":true,"description":"The good trousers","rating":4.5,"numReviews":12,"purchaseCost":80,"price":96,"countInStock":10,"}
The data is being properly queried and sent in the correct format, and yet I still have this error. Here is my server.js file, which contains my handler:
import path from 'path';
import express from 'express';
import dotenv from 'dotenv';
import cookieParser from 'cookie-parser';
dotenv.config();
import connectDB from './config/db.js';
import productRoutes from './routes/productRoutes.js';
import userRoutes from './routes/userRoutes.js';
import orderRoutes from './routes/orderRoutes.js';
import uploadRoutes from './routes/uploadRoutes.js';
import { notFound, errorHandler } from './middleware/errorMiddleware.js';
import ServerlessHttp from 'serverless-http';
connectDB();
const app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(cookieParser());
app.use('/api/products', productRoutes);
app.use('/api/users', userRoutes);
app.use('/api/orders', orderRoutes);
app.use('/api/upload', uploadRoutes);
app.use(notFound);
app.use(errorHandler);
const handler = ServerlessHttp(app, { provider: 'aws' });
export const run = async (context, req) => {
try {
context.res = await handler(context, req);
console.log("Server running");
console.log("Handler response:", context.res); // Log the handler response
} catch (e) {
console.log(e);
}
}
Any help would be wonderful!