0

我试图在 Netlify 上设置一个简单的无服务器函数,只是为了测试环境变量的使用。我在 Netlify 中为我的站点定义了以下两个环境变量:

变量的名称 价值
ALPHABET_SEPARATION 2
CHARS_BETWEEN 3

我还更新了我的函数目录,如下所示:

Functions directory:           myfunctions

我正在使用来自 github 的持续部署。由于我目前不知道 npm 的使用,并且发现直接测试生产部署很方便,所以我myfunctions在我的根目录中定义了一个名为的子目录,并将包含“无服务器”功能的 javascript 文件放在我的本地机器上. 我已经建立了逻辑,以便仅在设置“”标志时才调用“无服务器”函数netlify,否则,将在客户端执行备用函数。基本上它的工作原理如下:

const deploy = "netlify"  //Possible valid values are "local" and "netlify"

async function postRandomString() {
    const stringToUpdate = "THISISATESTSTRING"
    var stringToPost = "DUMMYINITIALVALUE";
    
    if (deploy === "local") {
        stringToPost = updateString(stringToUpdate); //updateString is a function defined elsewhere and executes client-side;
    }
    else if (deploy === "netlify") {

        const config = {
            method: 'GET',
            headers: {
                'Accept': 'application/json',
            }
        };

        const res = await fetch(`myfunctions/serverUpdateString?input=${stringToUpdate}`, config);
        const data = await res.json();

        stringToPost = data.retVal;
        console.log(data.retVal);
    }
    else {
        stringToPost = "##ERROR##";
    }

    postString(stringToPost); //postString is a function defined elsewhere and executes client-side;
}

serverless 函数文件serverUpdateString.js的编码如下(它基本上将字符串中某个位置CHARS_BETWEENALPHABET_SEPARATION由(不要问为什么 - 关键是它甚至从不接收/处理请求):

exports.handler = async function (event) {
    const { CHARS_BETWEEN, ALPHABET_SEPARATION } = process.env;
    const charsBetween = CHARS_BETWEEN;
    const alphabetSeparation = ALPHABET_SEPARATION;
    const initString = event.queryStringParameters.input;

    const rootUnicode = initString.charCodeAt(0);
    const finalUnicode = "A".charCodeAt(0) + (rootUnicode - "A".charCodeAt(0) + alphabetSeparation) % 26;
    const finalChar = String.fromCharCode(finalUnicode);

    const stringArray = initString.split("");
    stringArray[charsBetween + 1] = finalChar;

    const stringToReturn = stringArray.join("");

    const response = {
        statusCode: 200,
        retVal: stringToReturn,
    }

    return JSON.stringify(response);
}

当我运行它时,我收到 GET 请求的 404 错误: 控制台窗口中的错误 - script.js:43 是 const res = await fetch(myfunctions/serverUpdateString?input=ATESTSTRING, config);

在上图中,script.js:43const res = await fetch(myfunctions/serverUpdateString?input=ATESTSTRIN, config);调用文件中的行,如上面的第一个代码块所示。

我做错了什么?既然我已经正确指定了文件夹并将其放置在目录结构中的正确位置,那么 Netlify 应该能够获取无服务器功能文件吗?为了完整起见,我已经给出了整个代码,但问题似乎很简单。期待您的帮助,谢谢。

4

1 回答 1

0

我从 Netlify 论坛获得了帮助。基本上需要进行以下更改:

  1. 获取请求——调用代码 (script.js) 中的第 43 行——需要更改为
const res = await fetch(`https://netlifytestserverless.netlify.app/.netlify/functions/serverUpdateString?input=${stringToUpdate}`, config);
  1. 需要将 lambda 函数中的 return 语句更改为:
const response = {
    statusCode: 200,
    body: JSON.stringify(stringToReturn),
    }
  1. 其他小的更改,例如parseInt与环境变量一起使用。

该代码现在有效。

于 2021-05-15T14:37:06.720 回答