仅当满足条件时,AWS Lambda触发功能

时间:2019-10-25 19:05:16

标签: node.js amazon-cloudfront aws-lambda-edge

我刚刚开始使用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);  
};

1 个答案:

答案 0 :(得分:0)

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

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

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


    if (headers['cloudfront-viewer-country']) {
        // non IT url
        let url = '/en/';
        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); 
    }

    // There is no need to redirect
    callback(null, request);

};

因此,基本上,如果URL具有IT或EN,就让它通过白色: callback(null, request);

您可能会发现this example from the docs useful for your case