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

Netlify Lambda函数返回response undefined问题排查求助

核心问题

你遇到的response undefined报错和响应无法正常返回的问题,根源是以下几个编码错误:

  • 混用async/await和.then()链式调用,嵌套的表单提交axios.post没有加await,函数不等接口返回就直接执行到最后的return response,此时response还未被赋值
  • 嵌套在.then()中的返回值不会传递到外层的response变量,你没有等待整个Promise链执行完成就直接返回
  • 部分成功响应的body没有做JSON.stringify序列化,不符合Lambda函数的响应格式要求
  • 重复设置Content-Type请求头,formData.getHeaders()已经自带了正确的multipart/form-data类型,手动添加的配置会导致请求格式错误

优化后可直接运行的代码

const axios = require('axios');
const FormData = require('form-data');

const AUTH_API_ENDPOINT = 'https://www.mywebsite.com/wp-json/jwt-auth/v1/token/'
const FORM_API_ENDPOINT = 'https://www.mywebsite.com/wp-json/contact-form-7/v1/contact-forms/1217/feedback'
const captchaThreshhold = 0.5

exports.handler = async function(event, context) {
    const eventBody = JSON.parse(event.body)
    const captchaSecret = process.env.CAPTCHA_SECRET
    const captchaToken = eventBody.token
    const stringFormData = eventBody.formData
    const parsedFormData = JSON.parse(stringFormData)
    const formData = new FormData()

    // 构造FormData对象
    for (const key in parsedFormData) {
        formData.append(key, parsedFormData[key])
    }

    // 第一步:校验验证码
    let captchaRes
    try {
        captchaRes = await axios.post(`https://www.google.com/recaptcha/api/siteverify?secret=${captchaSecret}&response=${captchaToken}`, {})
    } catch(err) {
        return {
            statusCode: 200,
            body: JSON.stringify({
                status: 'error',
                message: 'Opps! The server tried to run an AI algorithm to determine if you are a spam robot, but the server did not respond properly so we are unable to continue contact form security verification... Please try again later or contact via phone instead. We appologize for the inconvenience.',
                error: err.message
            })
        }
    }
    
    // 验证码未通过
    if (captchaRes.data.score < captchaThreshhold) {
        return {
            statusCode: 200,
            body: JSON.stringify({
                status: 'error',
                message: "Error! Captcha Failed: our AI algorithms tried to determine if you are a robot or a human, it seems they couldn't decide, therefor for security reasons your form submission was blocked. Perhaps try again later, or contact via phone. We appologize for any inconvenience. :("
            })
        }
    }

    // 第二步:获取JWT凭证
    let jwtRes
    try {
        jwtRes = await axios.post(AUTH_API_ENDPOINT, {
            username: process.env.AUTH_USERNAME,    
            password: process.env.AUTH_PASSWORD,
        })
    } catch(err) {
        console.log('>>  获取JWT失败 ', err.response?.data || err.message);
        return {
            statusCode: 200,
            body: JSON.stringify({
                status: 'error',
                error: err.message,
                message: 'Yikes! The form data was processed and sent to our email server for authentication but got no response back.. This is a server issue so our developer will look into this shortly. In the meantime, please try again later or contact via phone. We appologize for the inconvenience.'
            })
        }
    }

    // 第三步:提交表单
    let formRes
    try {
        formRes = await axios.post(FORM_API_ENDPOINT, formData, {
            headers: {
                'Authorization': `Bearer ${jwtRes.data.token}`,
                ...formData.getHeaders()
            }
        })
        console.log('>> 表单提交成功: ', formRes.data.status, formRes.data.message)
        return {
            statusCode: 200,
            body: JSON.stringify({
                status: formRes.data.status,
                message: formRes.data.message
            })
        }
    } catch(err) {
        console.log('>> 表单提交失败 ', err.response?.data || err.message);
        return {
            statusCode: 200,
            body: JSON.stringify({
                status: 'error',
                error: err.message,
                message: 'Yikes! The form data was processed and sent to our email server but there was no response back. Our developer will look into this shortly. In the meantime, please try again later or contact via phone. We appologize for the inconvenience.'
            })
        }
    }
}

主要修改点

  • 全程用async/await替代嵌套的.then()链式调用,逻辑更清晰,避免异步执行顺序问题
  • 所有返回的响应body都统一做JSON.stringify序列化,符合Lambda返回规范
  • 删除了重复的Content-Type请求头配置,避免请求格式错误
  • 拆分了不同步骤的错误捕获,定位问题更方便,不会出现变量未赋值就返回的情况

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.14 06:27:01