【问题标题】:Issues With Netlify Lambda Function Response.. Keep Getting UndefinedNetlify Lambda 函数响应的问题.. 保持未定义
【发布时间】:2021-06-27 04:22:46
【问题描述】:

我正在尝试设置一个 lambda 函数来验证、验证和处理联系表单的发送..

我是 lambda 函数的新手,所以我的代码可能有缺陷,但无论我做什么,我似乎都无法修改发送回我的 vue.js 应用程序的响应。

我不断收到“未定义的响应”...

能否解释一下我做错了什么,也许是一种更好的方法来根据我的函数中发生的事情来更改返回的数据?

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
    let parsedFormData = JSON.parse(stringFormData)
    let formData = new FormData()
    var response;

    //build a new FormData object
    for ( var key in parsedFormData ) {
        formData.append(key, parsedFormData[key])
    }

    // first step is to validate the captcha..
    //let response_captcha
    try {
        response = 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 we're over the threshold we continue and get a fresh JWT
    if (response.data.score >= captchaThreshhold) {
        // let response_jwt
        try {
            response = await axios.post(AUTH_API_ENDPOINT,{
            username: process.env.AUTH_USERNAME,    
            password: process.env.AUTH_PASSWORD,
            }).then(res => {
                // JWT token returned something.. lets try to submit our form data with authentication code..
                axios.post(FORM_API_ENDPOINT, formData, {
                    headers: {
                        'Authorization': `Bearer ${res.data.token}`,
                        'Content-Type': 'multipart/form-data; charset="utf-8"',
                        ...formData.getHeaders()
                    }
                })
                .then( res => {
                    console.log('>> response came back from the Form endpoint : ',res.data.status, res.data.message)
                    return {
                        statusCode: 200,
                        body: {
                            status: res.data.status,
                            message: res.data.message
                        }
                        
                    }
                })
                .catch( err => {
                    console.log('>> something went wrong while trying to submit formData to form endpoint ',err.response.data);
                    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.'

                        })
                    }
                })
            }).catch( err => {
                    console.log('>> something went wrong while trying to fetch JWT from endpoint ',err.response.data);
                    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.'

                        })
                    }
                })
        } catch(err) {
            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 the server was unable to authenticate the request. 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.'

                })
            }
        }
    } else {
        // user failed the captcha test.. is probably a robot..
        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. :("
            })
        }
    }

    //send back the response..
    return response

}

【问题讨论】:

  • 首先,混合async/await.then - 你可以这样做,但是代码比它需要的复杂......问题可能是}).then(res => { // JWT token returned something.. lets try to submit our form data with authentication code.. axios.post -需要return axios.post那里

标签: javascript node.js vue.js aws-lambda netlify


【解决方案1】:

也许更像:

exports.handler = function(event, context) {
  return new Promise((resolve, reject) => {
    axios.post(...args).then(response => {
      if(bool){
        axios.post(...moreArgs).then(response => {
          resolve('ok!')
        }).catch(reject)
      } else {
        reject('not bool!')
      }
    }).catch(reject)
  })
}

我觉得 async / await 比没有它更复杂。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-10-22
    • 2020-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多