为何我的简单Lambda函数返回502 Internal Server Error?
Hey there, I see you’re hitting a 502 error when running your Lambda function, even though the logs show it executed successfully. That’s a super common gotcha when using Lambda with API Gateway—let me break down what’s going on and how to fix it.
The core issue here is that API Gateway expects your Lambda function to return a properly structured response object, not just a plain string. Your current code sends the message directly via callback(null, myMessage), which doesn’t meet API Gateway’s required format for proxy integrations.
Here’s the corrected version of your code that should resolve the 502 error right away:
'use strict'; console.log('Loading function'); exports.handler = (event, context, callback) => { let myMessage = "Testing this message thing."; // Format response to match API Gateway's requirements const response = { statusCode: 200, headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(myMessage), }; callback(null, response); };
Let me walk through the key changes:
- statusCode: This tells API Gateway what HTTP status to return (200 for a successful request).
- headers: Setting
Content-Typetoapplication/jsonensures the client knows how to parse the response correctly. - body: API Gateway requires the response body to be a string, so we use
JSON.stringify()to convert our message into a valid JSON string.
If you’re using a newer Node.js runtime (14.x or later), you might want to switch to async/await syntax for cleaner, more modern code—here’s how that would look:
'use strict'; console.log('Loading function'); exports.handler = async (event) => { let myMessage = "Testing this message thing."; return { statusCode: 200, headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(myMessage), }; };
This should eliminate the 502 error and return your message properly to the client.
内容的提问来源于stack exchange,提问作者Lee Fuller

