如何修改AWS Lambda Node.js代码以返回响应而非打印日志?
Fixing Your AWS Lambda to Return a Response Instead of Logging
Hey there! Let's tweak your AWS Lambda function to return the weather data as a proper HTTP response instead of just logging it to the console. The main issue with the original code is that it uses callback-style HTTP requests, which Lambda won't wait for by default—so the function would finish before the weather data is even fetched. Here's how to fix that:
Revised Code
exports.handler = async (event) => { const https = require('https'); // Wrap the HTTP request in a Promise to handle async logic cleanly const fetchWeatherData = () => { return new Promise((resolve, reject) => { https.get('https://api.openweathermap.org/data/2.5/weather?q=Auckland&appid=2eff2787a2d43a56539784f59bb8698a&units=metric', (resp) => { let data = []; // Collect incoming data chunks resp.on('data', (chunk) => { data.push(chunk) }); // Process the full response once it's received resp.on('end', () => { try { const parsedData = JSON.parse(data.toString()); resolve(parsedData); // Pass the parsed data to our Promise resolver } catch (parseError) { reject(new Error(`Failed to parse response: ${parseError.message}`)); } }); }).on("error", (requestError) => { reject(new Error(`Request failed: ${requestError.message}`)); }); }); }; try { // Wait for the weather data to be fetched const weatherData = await fetchWeatherData(); // Return a properly formatted Lambda response return { statusCode: 200, headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(weatherData), }; } catch (error) { // Handle errors and return an error response return { statusCode: 500, headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ error: error.message }), }; } };
Key Changes Explained
- Async Handler: We turned the handler into an
asyncfunction. This tells Lambda to wait for anyawaitoperations inside the function to complete before exiting, so it doesn't cut off our HTTP request early. - Promise Wrapper: Native
https.getuses callbacks, which can get messy. By wrapping it in a Promise, we can useawaitto handle the asynchronous flow in a more readable way. - Proper Response Format: Lambda requires responses to have a
statusCode, optionalheaders, and abody(which must be a string). We convert the parsed JSON data to a string withJSON.stringify()and set the correctContent-Typeheader. - Error Handling: We added a
try/catchblock to catch both HTTP request errors and JSON parsing errors. This ensures we return a meaningful error response instead of just logging the error.
内容的提问来源于stack exchange,提问作者Arun Nair
相关产品推荐
相关产品推荐

