0

I am working on a serverless application using AWS Lambda, a MYSQL database and API Gateway as Backend. I have several functions already working which use GET or POST methods to query the database. However, now I need to perform a query using data that the user selects in the web app. It is just a simple query, however, I am running with the following problem: when I send the query as a simple string, the API works well, although the query gives error (because I didn't send in the JSON format that Lambda works with). However, when I try to send a JSON object, the API gives the following error: Access to XMLHttpRequest at '...' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

This is my javascript code: `

var queryJSON = '{ "filter": "' + query + '"}';
function get_statistics() {
    $.ajax({
        url: "url...",
        type: "get",
        data: queryJSON,
        success: function(response) {
            console.log(response);
        },
        error: function(xhr) {
            console.log(xhr);
        }
    });
}`

Probably I am doing some mistake, but I don't manage to figure it out, thanks :)

MaxPower
  • 45
  • 1
  • 12
  • I don’t know if it applies to your case, but I get this error whenever I try to send or get data via HTTP instead of HTTPS. Of course, I mean when the CORS policy itself doesn’t block requests from other domains (even working locally from `localhost`). – Federico Moretti Mar 08 '20 at 14:00
  • I am sending to a HTTPS API, still the CORS is only giving problems if I send JSON string in the data field. – MaxPower Mar 08 '20 at 14:15
  • In the case where you send a JSON object and you get that CORS error, what’s the HTTP status code of the response? You can use the Network pane in browser devtools to check. Is it a 4xx or 5xx error rather than a 200 OK success response? – sideshowbarker Mar 08 '20 at 15:03
  • yes, it is a 400 error in the response header – MaxPower Mar 08 '20 at 17:01

1 Answers1

0

you can set up the required headers by using API Gateway method response and integration response settings. API Gateway will create an OPTIONS method and attempt to add the Access-Control-Allow-Origin header to your existing method integration responses. This doesn’t always work and sometimes you need to manually modify the integration response to properly enable CORS.

The following is an example of a Lambda function that is configured to return the required CORS headers:

exports.handler = function(event, context) {
    var response = {
        statusCode: 200,
        headers: {
            "x-custom-header" : "custom header value",
            "Access-Control-Allow-Origin": "*"
        },
        body: {}
    }; 
    context.succeed(response)
}

hope it would fix your problem, please make sure your request and response headers are same.