2 回答
TA贡献2039条经验 获得超7个赞
要启用cors连接到 lambda 函数的 api 网关端点,您必须为 api 端点启用 cors(您已经完成)并配置您的 lambda 函数 suport cors。
按照我的例子:
// 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"}
}
}
我的方式仅在 api 网关使用LAMBDA-PROXY事件配置时生效(默认)
TA贡献1877条经验 获得超6个赞
您可以从 api 网关启用 cors 您可以从 lambda 管理 cors 并从 lambda 管理标头。
我建议从 api 网关启用 cors 并测试它是否可以工作。
你可以管理access-control-origin并headers喜欢这种方式
'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);
};
您可以参考此文档: https ://serverless.com/framework/docs/providers/aws/events/apigateway/
添加回答
举报