【问题标题】:API Gateway -> Lambda -> DynamoDB using Cognito. HTTP POST-> Unable to read response but returns a code 200API 网关 -> Lambda -> 使用 Cognito 的 DynamoDB。 HTTP POST-> 无法读取响应但返回代码 200
【发布时间】:2019-03-18 17:27:40
【问题描述】:

场景: 我查询了一个 HTTP POST(使用 Authorizer 作为 Cognito 的 Header 参数)。 当我尝试获取/读取查询响应时,它会触发错误事件。但是,在浏览器中,我可以看到 2 个 HTTP POST 响应如何使用 200 个代码,其中一个返回有效响应。例如:如果我通过 POST 人发出请求,我会以一种很好的方式在 1 个响应中收到数据。

问题: 我无法打印结果,因为它使用无效的响应数据启动错误事件。

浏览器图片https://i.postimg.cc/MTMsxZjw/Screenshot-1.png https://i.postimg.cc/3RstwMgv/Screenshot-2.png

Lambda 代码

'use strict';

var AWS = require('aws-sdk'),
    documentClient = new AWS.DynamoDB.DocumentClient(); 

exports.handler = function index(event, context, callback){
    var params = {
        TableName : "data-table"
    };
    documentClient.scan(params, function(err, data){
        if(err){
            callback(err, null);
        }else{
            console.log(JSON.stringify(data.Items));
            callback(null, data.Items);
        }
    });
}

客户端 JS 代码

function requestData(pickupLocation) {
    $.ajax({
        type: 'POST',
        url: _config.api.invokeUrl,
        headers: {
            Authorization: authToken,
        },
        data: "{}",
        cache: false,
        success: completeRequest,
        error: errorRequest
    });
}

function completeRequest(response) {
    alert("hello");
    alert(response.d);
}

function errorRequest(response) {
    alert("hello1");
    alert(response.status + ' ' + response.statusText);
}

【问题讨论】:

  • 能否请您分享非图片格式的回复详细信息?
  • CORS 策略已阻止从源“null”访问“https://***.execute-api.eu-west-1.amazonaws.com/prod/recurso”处的 XMLHttpRequest :请求的资源上不存在“Access-Control-Allow-Origin”标头。跨域读取阻止 (CORB) 阻止了具有 MIME 类型 application/json 的跨域响应 https://***.execute-api.eu-west-1.amazonaws.com/prod/recurso。更多详情请见chromestatus.com/feature***
  • 这看起来您的 API 网关已禁用 CORS。我知道您提到它已启用,但您可以尝试再次启用它并将其保留为默认值,然后执行“部署 API”并查看它是否有效?
  • 太棒了!它解决了这个问题。但这是一个诡计。当您启用 CORS 时,您必须添加 Access-Control-Allow-Origin*(它隐藏在高级选项中)
  • 很高兴听到,我添加了评论作为答案,因此您可以将其标记为已解决(使用复选标记选项)

标签: amazon-web-services api lambda amazon-cognito


【解决方案1】:

根据基于 cmets 的进一步澄清,这看起来 API 网关禁用或启用了 CORS,但标头值返回不正确。

解决方案是通过 API 网关重新启用 CORS,并在高级选项中将 Access-Control-Allow-Origin 添加到标头响应中(如果默认情况下尚未启用)。

【讨论】:

    【解决方案2】:

    如果您要代理响应,则需要遵循特定格式described here

        'use strict';
    console.log('Loading hello world function');
     
    exports.handler = async (event) => {
        let name = "you";
        let city = 'World';
        let time = 'day';
        let day = '';
        let responseCode = 200;
        console.log("request: " + JSON.stringify(event));
        
        // This is a simple illustration of app-specific logic to return the response. 
        // Although only 'event.queryStringParameters' are used here, other request data, 
        // such as 'event.headers', 'event.pathParameters', 'event.body', 'event.stageVariables', 
        // and 'event.requestContext' can be used to determine what response to return. 
        //
        if (event.queryStringParameters && event.queryStringParameters.name) {
            console.log("Received name: " + event.queryStringParameters.name);
            name = event.queryStringParameters.name;
        }
        
        if (event.pathParameters && event.pathParameters.proxy) {
            console.log("Received proxy: " + event.pathParameters.proxy);
            city = event.pathParameters.proxy;
        }
        
        if (event.headers && event.headers['day']) {
            console.log("Received day: " + event.headers.day);
            day = event.headers.day;
        }
        
        if (event.body) {
            let body = JSON.parse(event.body)
            if (body.time) 
                time = body.time;
        }
     
        let greeting = `Good ${time}, ${name} of ${city}. `;
        if (day) greeting += `Happy ${day}!`;
    
        let responseBody = {
            message: greeting,
            input: event
        };
        
        // The output from a Lambda proxy integration must be 
        // of the following JSON object. The 'headers' property 
        // is for custom response headers in addition to standard 
        // ones. The 'body' property  must be a JSON string. For 
        // base64-encoded payload, you must also set the 'isBase64Encoded'
        // property to 'true'.
        let response = {
            statusCode: responseCode,
            headers: {
                "x-custom-header" : "my custom header value"
            },
            body: JSON.stringify(responseBody)
        };
        console.log("response: " + JSON.stringify(response))
        return response;
    };

    【讨论】:

    • 代理响应是什么意思?我只是使用从 Cognito 获得的 Auth 令牌查询 lambda 函数
    • 他们的意思是,如果您有 API 网关充当您的 Lambda 的代理(看起来这就是您所设置的),您应该以正确的格式返回响应。所以从你的角度来看,你所要做的就是改变回调(null,data.Items);,做回调(null,response)并使用上面的响应格式
    • 它不起作用。让响应 = { statusCode: 200, headers: { "Access-Control-Allow-Origin" : "" }, body: JSON.stringify(data.Items) }; console.log("响应:" + JSON.stringify(响应));回调(空,响应);响应:{ "statusCode": 200, "headers": { "Access-Control-Allow-Origin": "" }, "body": "[{\"tap\":\"001\" ,\"id\":\"1\"}]" }
    【解决方案3】:

    如果您使用的是 chrome,您可能需要 cors plugin

    【讨论】:

    • 我无法设计基于扩展的解决方案。无论如何感谢您的回复
    • 如果您正在使用,您也可以通过 api-gateway 启用它。
    • API网关开启
    • 对不起,除了插件我什么都不知道。
    猜你喜欢
    • 2017-01-29
    • 1970-01-01
    • 1970-01-01
    • 2019-02-10
    • 2019-12-12
    • 2020-11-11
    • 2012-08-14
    • 2016-04-27
    • 2021-08-09
    相关资源
    最近更新 更多