问题描述
我正在尝试在 Netlify 上设置一个简单的无服务器功能,以测试环境变量的使用情况。我在 Netlify 中为我的站点定义了以下两个环境变量:
变量名 | 值 |
---|---|
ALPHABET_SEParaTION | 2 |
CHARS_BETWEEN | 3 |
我还更新了我的函数目录如下:
Functions directory: myfunctions
我正在使用来自 github 的持续部署。由于我目前不知道 npm 的使用,并且发现直接测试生产部署很方便,我在我的根目录中定义了一个名为 myfunctions
的子目录,并将包含“serverless”功能的 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;
}
无服务器函数文件serverUpdateString.js
的编码如下(它基本上将字符串中某个位置(由CHARS_BETWEEN
确定)的字符设置为某个数字(由ALPHABET_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);
}
) 在字符串的第一个字符之后的字母表中的位置(不要问为什么 - 重点是它甚至从不接收/处理请求):
script.js:43
当我运行它时,我收到 GET 请求的 404 错误:
在上图中,const res = await fetch(myfunctions/serverUpdateString?input=ATESTSTRIN,config);
是调用文件中的第 http://some.domain/json.PHP?key=%DF
行,如上面的第一个代码块所示。
我做错了什么?考虑到我已经指定了文件夹并将其放置在目录结构中的正确位置,Netlify 应该能够获取无服务器函数文件吗?我已经给出了完整的代码,但问题似乎很基本。期待您的帮助,谢谢。
解决方法
我从 Netlify 论坛获得了帮助。基本上需要进行以下更改:
- 获取请求 -- 调用代码 (script.js) 中的第 43 行 -- 需要更改为
const res = await fetch(`https://netlifytestserverless.netlify.app/.netlify/functions/serverUpdateString?input=${stringToUpdate}`,config);
- 需要将 lambda 函数中的 return 语句更改为:
const response = {
statusCode: 200,body: JSON.stringify(stringToReturn),}
- 其他小的更改,例如将
parseInt
与环境变量一起使用。
代码现在可以运行了。