You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改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 async function. This tells Lambda to wait for any await operations inside the function to complete before exiting, so it doesn't cut off our HTTP request early.
  • Promise Wrapper: Native https.get uses callbacks, which can get messy. By wrapping it in a Promise, we can use await to handle the asynchronous flow in a more readable way.
  • Proper Response Format: Lambda requires responses to have a statusCode, optional headers, and a body (which must be a string). We convert the parsed JSON data to a string with JSON.stringify() and set the correct Content-Type header.
  • Error Handling: We added a try/catch block 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 11:02:58