简体   繁体   English

在Java中的AWS lambda函数中包括Access-control-header

[英]Including Access-control-header in AWS lambda function in java

I have been trying to deploy a lambda function and then make it accessible through API-gateway. 我一直在尝试部署lambda函数,然后通过API网关对其进行访问。 My java function is in JAVA and this is the documentation I followed to create a simple AWS lambda function in JAVA: 我的Java函数在JAVA中,这是我在JAVA中创建简单的AWS lambda函数所遵循的文档:

https://docs.aws.amazon.com/lambda/latest/dg/java-handler-io-type-pojo.html https://docs.aws.amazon.com/lambda/latest/dg/java-handler-io-type-pojo.html

This is how my function handler looks: 这是我的函数处理程序的外观:

package lambda;

    import com.amazonaws.services.lambda.runtime.Context;
    import com.amazonaws.services.lambda.runtime.RequestHandler;
    import lambda.axon.Path;

    public class shortestPath implements RequestHandler<RequestClass, ResponseClass>{

        public ResponseClass handleRequest(RequestClass request, Context context){
            String inputString = request.inputString;
            int steps = Path.stepsTo(inputString);
            return new ResponseClass(steps);

        }
    }

This is this request class: 这是此请求类:

package lambda;

public class RequestClass {
    String inputString;

    public String getInputString() {
        return inputString;
    }

    public void setInputString(String inputString) {
        this.inputString = inputString;
    }


    public RequestClass(String inputString) {
        this.inputString = inputString;
    }

    public RequestClass() {
    }
}

And this the response class: 这是响应类:

package lambda;

public class ResponseClass {
    int steps;

    public ResponseClass(int steps) {
        this.steps = steps;
    }

    public ResponseClass() {
    }
    public int getSteps() {
        return steps;
    }

    public void setSteps(int steps) {
        this.steps = steps;
    }


}

I deploy this on aws and configure AWS api gateway to trigger it , everything works fine when I hit the end-point given by the API gateway when I use postman( https://www.getpostman.com/ ) 我将其部署在aws上并配置AWS api网关来触发它,当我使用postman( https://www.getpostman.com/ )到达API网关给定的端点时,一切工作正常

But trying the same through a browser gives me a CORS error: 但是通过浏览器尝试同样的操作会给我一个CORS错误:

Access to XMLHttpRequest at 'https://<hash>execute-api.us-east-1.amazonaws.com/dev' from origin 'http://localhost:4200' has been blocked by CORS policy: Request header field access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response.

I tried enabling CORS in the API gateway console and then redeploying it: 我尝试在API网关控制台中启用CORS,然后重新部署它: 在此处输入图片说明

This Stackoverflow post( Configure CORS response headers on AWS Lambda? ) says if I am using a lambda-proxy I should have the headers in the handler response itself, I am not sure what a proxy is but how I can do that with my current implementation of the Lambda function ie include custom headers in my Response 这篇Stackoverflow帖子( 在AWS Lambda上配置CORS响应标头? )说,如果我使用lambda-proxy,我应该在处理程序响应本身中包含标头,但我不确定代理是什么,但是如何使用当前的代理来做到这一点。函数的实现,即在我的响应中包含自定义标头

To enable cors for a api gateway endpoint what connects to a lambda function, you have to enable cors for api endpoint (you have done) AND config your lambda function suport cors . 要启用cors的API网关端点什么连接到拉姆达功能,您必须启用API端点CORS(你这样做)和配置您的lambda表达式询问服务cors

Follow my example: 跟随我的例子:

// new respose class, replace for your class - ResponseClass
public class Response {

    private int statusCode; // http status code

    private Map<String, String> headers; // headers

    private String body; // body - what you want to return to client

    public Response(int statusCode, Map<String, String> headers, String body) {
        this.statusCode = statusCode;
        this.headers = headers;
        this.body = body;
    }

    public int getStatusCode() {
        return statusCode;
    }

    public Map<String, String> getHeaders() {
        return headers;
    }

    public String getBody() {
        return body;
    }

    public void setStatusCode(int statusCode) {
        this.statusCode = statusCode;
    }

    public void setHeaders(Map<String, String> headers) {
        this.headers = headers;
    }

    public void setBody(String body) {
        this.body = body;
    }

}

/// -------------

package lambda;

    import com.amazonaws.services.lambda.runtime.Context;
    import com.amazonaws.services.lambda.runtime.RequestHandler;
    import lambda.axon.Path;

    public class shortestPath implements RequestHandler<RequestClass, Response>{

        public Response handleRequest(RequestClass request, Context context){
            String inputString = request.inputString;
            int steps = Path.stepsTo(inputString);

            Map<String, String> headers = new HashMap<>();
            headers.put(Access-Control-Allow-Origin, "*"); // cors header, you can add another header fields

            return new Response(200, headers, "" + steps);
            // return new Response(200, headers, "{result: " + steps + "}");
            // simple json response. ex: {result: '3433"}
        }
    }

My way only effect when api gatewateway use LAMBDA-PROXY event config (default) 我的方式仅在api gatewateway使用LAMBDA-PROXY事件配置时有效(默认)

在此处输入图片说明

you can enable cors from api gateway you can manage cors from lambda and manage the headers from lambda. 您可以从api网关启用cors,也可以从lambda管理cors和从lambda管理标头。

i would suggest to enable cors from api gateway and test it will work. 我建议从api网关启用cors并测试它是否可以工作。

you can manage access-control-origin and headers like this way 您可以access-control-origin这种方式管理access-control-originheaders

'use strict';

module.exports.hello = function(event, context, callback) {

const response = {
  statusCode: 200,
  headers: {
    "Access-Control-Allow-Origin" : "*", // Required for CORS support to work
    "Access-Control-Allow-Credentials" : true // Required for cookies, authorization headers with HTTPS 
  },
  body: JSON.stringify({ "message": "Hello World!" })
};

callback(null, response);
};

you can refer this documentation : https://serverless.com/framework/docs/providers/aws/events/apigateway/ 您可以参考以下文档: https : //serverless.com/framework/docs/providers/aws/events/apigateway/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM