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

AWS Lambda调用外部REST API遇两类错误,请求技术排查

错误修复方案

错误1:TypeError: Cannot read properties of undefined (reading 'abc')

  • 问题原因:defaultOptions里的host字段写法错误,event.xyz.abc.com试图把abc.com当作event.xyz的属性访问,但实际你要设置的是域名字符串,且event.xyz大概率未定义,导致读取属性失败。
  • 修复方法:如果域名是固定值,直接写字符串形式"xyz.abc.com";如果域名来自event的某个字段(比如event.host),则改为event.host。

错误2:语法错误 unexpected token /

  • 问题原因:event./userId是非法JavaScript语法,你想传递的是路径字符串,要么是固定路径"/userId",要么是需要拼接event中的userId变量(比如"/users/" + event.userId)。
  • 修复方法:根据实际需求修正路径参数,固定路径直接写"/userId";动态路径用模板字符串"/users/${event.userId}"。

额外问题:GET请求不应写入请求体

原代码中getStatus函数定义的是GET请求,但调用了req.write(JSON.stringify(payload)),GET请求不需要发送请求体,这会导致请求异常,必须删除该行。

完整修正代码

const https = require('https'); // 补充引入https模块,原代码遗漏该依赖

const getStatus = (defaultOptions, path, payload) => new Promise((resolve, reject) => {
    const options = { ...defaultOptions, path, method: 'GET' };
    const req = https.request(options, res => {
        let buffer = "";
        res.on('data', chunk => buffer += chunk);
        res.on('end', () => {
            // 增加JSON解析错误捕获,避免非JSON响应导致崩溃
            try {
                resolve(JSON.parse(buffer));
            } catch (e) {
                reject('JSON解析失败: ' + e.message);
            }
        });
    });
    req.on('error', e => reject(e.message));
    // 删除GET请求的write操作
    req.end();
});

exports.handler = async (event) => {
    // 修复host字段为固定域名字符串
    const defaultOptions = {
        host: "xyz.abc.com", 
        port: 443,
        headers: {
            'Content-Type': 'application/json',
            'Authorization': 'Bearer 12345432157'
        }
    };
    
    // 修复路径参数为合法字符串
    var status_info = await getStatus(defaultOptions, "/userId", ''); 

    const response = {
        statusCode: 200,
        body: JSON.stringify(status_info),
    };
    return response;
};

内容的提问来源于stack exchange,提问作者Kanna

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 23:05:30