I am getting CORS error when making ajax request to the AWS lambda function url from browser.
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://somethingsomething.lambda-url.us-east-2.on.aws/authnz/subscribe. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). Status code: 200.
My Lambda Function URL’ CORS is configured as below . However, browser is still throwing error when my JQUERY makes POST call.
JQuery call:
$.ajax({
url: remoteUrl,
type: "POST",
contentType: "application/json",
headers: {
"Authorization": "Bearer "+token
},
data: {"a":"aa"},
success: function(response) {
console.log(response);
},
error: function(xhr) {
$("#form_save_message").show();
}
});
});
The response headers for the OPTIONS
calls are
How can I get the CORS working for the POST to the Lambda function URL? I am not using API gateway just the Lambda function URL. Do I must use API Gateway ? From what I have seen every question here is with API gateway + Lambda.
My Backend code, just have some business logic and looks like this :
public class RegistrationApplication implements RequestHandler<Map<String, Object>, Map<String, Object>> {
@Override
public Map<String, Object> handleRequest(Map<String, Object> requestParams, Context context) {
Map<String,Object> lambdaResponse = new HashMap<>();
return lambdaResponse;
}
}
Note,
- my lambda is written in Java
- I am not seeing the lambda handler logs rolling when OPTIONS calls is made by browser so adding headers in the function
public Map<String, Object> handleRequest(Map<String, Object> requestParams, Context context) {
will have no effect.
2
Answers
After quite some online reading, debugging and taking help from other comments I figured out that my jQuery was sending
content-type
andauthorization
headers.So there are two ways to fix this:
content-type
headers because of this linecontentType: "application/json"
. So I updated the jquery todataType: "json",
. 2.You add both the headers in the "Allow headers" of the Function URL.This article explains how to debug CORS: https://medium.com/@mail.ekansh/cors-with-lambdas-function-url-22bb5bfcb3c4
For me, CORB issue happened when I had configured the API Gateway with proper CORS configurations, but my Lambda function written in .NET was not returning proper CORS header in the response. This was resulting in successful OPTIONS request but was failing while making GET or POST requests to the API Gateway.
A simple solution for you would be to return
Access-Control-Allow-Origin
header from your Java Lambda function.I am not a JAVA guy, so please excuse me if I am wrong below. But this is just to show you how can you return the required header from the Lambda function.