【问题标题】:AWS Lambda trigger function only if conditions are metAWS Lambda 仅在满足条件时触发函数
【发布时间】:2020-02-22 03:36:02
【问题描述】:

我刚刚开始学习 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);  
};

【问题讨论】:

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


    【解决方案1】:

    如果我没记错,那么您缺少的部分是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,就让它通过 whit: callback(null, request);

    你可能会找到this example from the docs useful for your case

    【讨论】:

    • 基本上,我缺少的是在末尾添加callback(null, request)。在这种情况下,实际上没有发生重定向,请求按原样传递到源。
    猜你喜欢
    • 1970-01-01
    • 2021-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-11
    • 2017-12-12
    • 2016-09-17
    • 1970-01-01
    相关资源
    最近更新 更多