首页 > 解决方案 > Netlify lambda 函数查询字符串参数在本地环境和生产环境之间以不同的方式传递

问题描述

描述错误

我创建了几个 lambda 函数并将它们部署在 Netlify 服务上。

我通过 GET 请求传递了几个查询,它们在本地作为数组传递,但一旦部署,它们就作为字符串传递。

重现行为的重现 步骤:

lambda函数方面:

export const handler = constructNetlifyHandler({
  get: async (event, context, postgrest) => {
    console.log(event.queryStringParameters);

    return await getAllTasks(
        postgrest,
        event.queryStringParameters,
        event.loggedInUserOrg
    );
  },
});

邮递员方面:

{{host}}/tasks?orgUid=06ea7872-32eb-4e7a-ba45-63e2b9e6c747&statusUid=ba92a0b7-2e80-4cd2-8d37-fa18d5ca22b9&statusUid=78dcdbe1-007a-493a-ad94-50a0ec613d0d&statusUid=1cbc65b8-831d-4cba-a1ad-111a0757e76b

本地环境的日志:

{
  orgUid: '06ea7872-32eb-4e7a-ba45-63e2b9e6c747',
  statusUid: [
    'ba92a0b7-2e80-4cd2-8d37-fa18d5ca22b9',
    '78dcdbe1-007a-493a-ad94-50a0ec613d0d',
    '1cbc65b8-831d-4cba-a1ad-111a0757e76b'
  ]
}

登录 netlify 生产环境:

{
  orgUid: '06ea7872-32eb-4e7a-ba45-63e2b9e6c747',
  statusUid: 'ba92a0b7-2e80-4cd2-8d37-fa18d5ca22b9, 78dcdbe1-007a-493a-ad94-50a0ec613d0d, 1cbc65b8-831d-4cba-a1ad-111a0757e76b'
}

预期行为

在这两种环境中,查询参数以相同的方式传递。(作为字符串数组或字符串)

截图

邮递员方面: 图片

本地环境的日志:

图片

生产环境日志:

图片

桌面(请填写以下信息): 运行以下命令npx envinfo --system --binaries --npmPackages netlify-lambda并附加输出

附加上下文

 System:
    OS: macOS 11.2.3
    CPU: (4) x64 Intel(R) Core(TM) i3-9100 CPU @ 3.60GHz
    Memory: 54.82 MB / 24.00 GB
    Shell: 5.8 - /bin/zsh
  Binaries:
    Node: 12.20.1 - ~/.nvm/versions/node/v12.20.1/bin/node
    Yarn: 1.22.10 - /usr/local/bin/yarn
    npm: 6.14.10 - ~/.nvm/versions/node/v12.20.1/bin/npm
    Watchman: 4.9.0 - /usr/local/bin/watchman
  npmPackages:
    netlify-lambda: ^2.0.3 => 2.0.3 

标签: lambdanetlifyquery-parametersnetlify-function

解决方案


解决方案 1:在函数内部进行匹配

由于 Netlify 重定向机制无法为您提供它匹配的规则的数据,您可以尝试匹配函数中的原始请求以确定它应该做什么。

例子:

_重定向

> /first-thing /.netlify/functions/the-only-function 200! /second-thing
> /.netlify/functions/the-only-function 200! 

the-only-function.js

exports.handler = async function(event, context) {
    if (event.path === "/first-thing") {
        // do one thing
    } else if (event.path === "/second-thing") {
        // do the other thing
    } else {
        // return 400 status, because the function was invoked raw
    }
}

解决方案 2:代理标头 hack

当您重写某些内容时,您可以添加自定义代理标头(单击查看文档)1。

使用这些解决了相同的示例:

netlify.toml

[[redirects]]
from = "/first-thing"
to = "/.netlify/functions/the-only-function"
status = 200
force = true
headers = {X-Variant = "first-thing"}

[[redirects]]
from = "/second-thing"
to = "/.netlify/functions/the-only-function"
status = 200
force = true
headers = {X-Variant = "second-thing"}

the-only-function.js

exports.handler = async function(event, context) {
    if (event.headers["X-Variant"] === "first-thing") {
        // do one thing
    } else if (event.headers["X-Variant"] === "second-thing") {
        // do the other thing
    } else {
        // return 400 status, because the function was invoked raw
    }
}

希望这可以帮助您解决您的具体问题!

这是参考


推荐阅读