仅当满足条件时,AWS Lambda触发函数

问题描述 投票:0回答:1

我刚刚开始使用AWS Lambda和CloudFront进行学习。我发现很容易操纵请求和响应,但是我无法完成一个简单的任务。

给出下面的代码,我只想在用户在request.uri中没有/ it /或/ en /的情况下才触发操作>

我在解析uri字符串时没有问题,但是我不确定如何实现这个非常简单的逻辑:

if(uri contains 'it' or 'en') {
  proceed as normal and forward request to origin
} else {
  return a 301 response with '/it' or '/en' based on user language
}

用node.js编写的下面的函数部分地完成了这项工作,它是在我的CloudFront发行版的Viewer Request中触发的:

exports.handler = async (event, context, callback) => {

    // const
    const request = event.Records[0].cf.request;
    const headers = request.headers;

    // non IT url
    let url = '/en/';
    if (headers['cloudfront-viewer-country']) {
        const countryCode = headers['cloudfront-viewer-country'][0].value;
        if (countryCode === 'IT') {
            url = '/it/';
        }
    }

    const response = {
        status: '301',
        statusDescription: 'geolocation',
        headers: {
            location: [{
                key: 'Location',
                value: url,
            }],
        },
    };

    callback(null, response);  
};

我刚刚开始使用AWS Lambda和CloudFront进行学习。我发现操纵请求和响应非常容易,但是我无法完成一个简单的任务。给定下面的代码,我想要...

node.js amazon-cloudfront aws-lambda-edge
1个回答
0
投票

如果我没记错的话,您缺少的部分是if,因为您只有else

© www.soinside.com 2019 - 2024. All rights reserved.