Struggling to overcome CORS error while trying to retrieve AWS Lambda response through a basic HTTP Api Gateway request

Currently, I am facing an issue with my API setup. The process involves a Website calling API Gateway, which invokes Lambda to fetch data from MySQL Table and display it on the website. While using Postman, I am able to retrieve the data successfully. However, when trying to fetch it through JavaScript code, I encounter CORS errors. I suspect that the issue might not be solely related to CORS but could be caused by an error in my Lambda function. The console displays these errors:https://i.sstatic.net/uXQT7.pngHere is the snippet of my web side code used to call the gateway:

const Http = new XMLHttpRequest();
const url = 'https://nnebmzru3e.execute-api.us-east-2.amazonaws.com/proxy+';
    
Http.open("OPTIONS", url);
Http.setRequestHeader('Access-Control-Allow-Origin', '*');

Http.send();
console.log(Http.responseText)
Http.onreadystatechange = (e) => {
    console.log(Http.responseText)
}

This is how my Lambda code looks like:

const mysql = require("mysql");

exports.handler = (event, context, callback) => {
    console.log(event);
    const connection = mysql.createConnection({
        host: process.env.RDS_HOSTNAME,
        user: process.env.RDS_USERNAME,
        password: process.env.RDS_PASSWORD,
        port: process.env.RDS_PORT,
    });

    connection.query(
        "SELECT * FROM pickemss.pickems where Week = 1",
        function (error, results, fields) {
            if (error) {
                console.log("ERROR DESTROYING CONNECTION");
                connection.end();
                throw error;
            } else {
                // connected!
                console.log("CONNECTED");
                connection.end(function (err) {
                    callback(err, formatResponse(results));
                });
            }
        }
    );
};

var formatResponse = function (body) {
    console.log("Formatting response");
    var response = {
        statusCode: 200,
        headers: {
            "Access-Control-Allow-Origin": "*",
            "Access-Control-Allow-Headers": "Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token",
            "Access-Control-Allow-Methods": "*",
        },
    };
    response.body = JSON.stringify(body);
    console.log(response.body);

    return response;
};

I have attempted to use a GET request on a different route, but I am perplexed as to why it is failing since there are no errors in my CloudWatch logs and the data from the MySQL query is visible as well.

Answer №1

Your function appears to have a problem with returning the CORS headers correctly, affecting its intended functionality. The code structure is also quite challenging to decipher. While AWS lambda offers a third parameter for function handlers (callback), it's now discouraged due to callback hell, increased bug vulnerability, and readability issues. To address this, consider implementing the following revised code:

const mysql = require("mysql");

function fetchData(connection, query) {
  return new Promise((resolve, reject) => {
    connection.query(query, function (error, results) {
      if (error) {
        console.log("ERROR - CONNECTION TERMINATED");
        connection.end();
        reject(error);
        return;
      }

      console.log("CONNECTION SUCCESSFUL");
      connection.end();
      resolve(results);
    });
  });
}

function determineResponse(data) {
  const responseObj = {
    statusCode: 200,
    headers: {
      "Access-Control-Allow-Origin": "*",
      "Access-Control-Allow-Headers":
        "Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token",
      "Access-Control-Allow-Methods": "*",
      body: JSON.stringify(data),
    },
  };

  return responseObj;
}

exports.handler = async (event) => {
  console.log(event);
  const dbConnection = mysql.createConnection({
    host: process.env.RDS_HOSTNAME,
    user: process.env.RDS_USERNAME,
    password: process.env.RDS_PASSWORD,
    port: process.env.RDS_PORT,
  });
  const query = "SELECT * FROM pickemss.pickems where Week = 1";
  const retrievedData = await fetchData(dbConnection, query);

  return determineResponse({ retrievedData });
};

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Disable the button if the textbox is not empty

I need assistance with a way to remove the disabled attribute from a button if textboxes with the class 'number' have values inside, and then disable it again if the textbox is emptied. Here's the current code snippet: <input type="text ...

Iterating through records in a MySQL stored procedure

If I have a set of numbers stored in a table column like 1,60,71, how can I create a loop in SQL within a stored procedure to iterate through these numbers? This is what I need: Loop through 1, 60, and 71 Update rows with corresponding IDs (1, 60, 71) by ...

Attempting to insert the symbol "$gt" into a query for a search. {[CastError: Unable to convert value "[object Object]" to date at path "createdAt"]}

In the following code snippet: Reviews.find({createdAt : {"$lt" : app.locals.lastDate}}), I am trying to dynamically change the $lt to $gt. app.post("/scroll", function(req, res){ console.log("req.body...", req.body); var sortCreate = req.body.old ...

The data input from the HTML is not being correctly transferred to the modal

I am trying to transfer the reservation id from an HTML element to a modal window. When I click "cancel" next to a reservation, a modal should appear showing the reservation id. However, the modal pops up without displaying the reservation id. Can anyone h ...

React - navigating with hash in routing parameter

I am facing an issue with my application, where I have implemented navigation between different cars. Each car has a unique ID, but some IDs contain a hash symbol, like 'test#car#1'. This hash symbol in the ID is causing problems with the navigat ...

Tips for including multiple directives in a component

Apologies in advance for my lack of clarity in expressing this question, which is why I am seeking assistance rather than finding the solution on my own. My query pertains to loading a component within another one and specifying it in the directive. Below ...

What is the significance of using $timeout in order to activate a watch function?

There is an interesting phenomenon happening with my directive. It watches the height of an element that is being updated by a controller using a factory method to retrieve data. Strangely, unless I include a $timeout in that factory function, my watch doe ...

Safari 7.0 Experiencing Unpredictable Ajax Errors

Encountered an issue with Ajax requests through jQuery on a web app while using Safari 7.0 for Mac OS X 10.9 Mavericks (specifically 9537.71). This problem was occurring intermittently and could not be reproduced consistently on Safari 7.0. Environment: ...

Utilizing Jquery during a partial postback within an updatepanel

I am facing an unusual issue related to JQuery and partial postback on an updatepanel. What I have tried is implementing a jQuery logic in the code-behind using: Page.ClientScript.RegisterStartupScript(this.GetType(), "jsSlider" + select.ClientID, sb.ToS ...

Extracting props data from a component in React.js - a step-by-step guide

I am currently developing a react.js application with react-select. I have created a dropdown menu and when an item is clicked, I need to pass that item to a function that is connected to the redux store. How can I retrieve data from a component used in re ...

receiving a result from an asynchronous operation

Is there a way to retrieve the return value from this code snippet without using console log? function get_disk_space(callback){ checkDiskSpace('C:\\').then((diskSpace) => { var free = Math.floor(diskSpace.free/1000000000) ...

Using Selenium in Java: Implementing a line break in a webpage and executing it

On the current page, I need to insert a <br> tag into a specific section. The HTML code below shows where I want to make this addition: <p style="font-size:13pt; line-height:130%; margin:0pt; orphans:0; text-align:center; widows:0"> <span c ...

Ways to retrieve all elements, including those that are hidden, within a CSS grid

My goal is to retrieve all the "Available Items" using Javascript in one go. However, I am facing an issue where not all of them are visible at once due to the need to manually scroll through a CSS grid. <div class="gridWrapper" data-dojo-attach-point= ...

Revert the Vue State When Navigating Back in the Browser

Background In our checkout process, we redirect to Stripe after creating an order object through an API request. To prevent users from clicking the "checkout" button multiple times during this process, we toggle a variable value to show a loading icon whe ...

Generating basic mesh shapes using three.js programmatically

Is there a way to easily generate basic shapes such as ramps, cones, and revolution shapes using only their vertices in three.js? ...

Having trouble utilizing a function with an async onload method within a service in Angular - why does the same function work flawlessly in a component?

I successfully created a component in Angular that can import an Excel file, convert it into an array, and display its content as a table on the page. The current implementation within the component looks like this: data-import.compoent.ts import { Compo ...

An effective way to verify if a record has been successfully updated is by utilizing Sequelize's

Within this snippet of code, I made an update to a specific record in the IPAdress model. What is the best way for me to verify if the record has been successfully updated or not? let IPAdress = await model.IPAdress.update(data,{ where: { id } }); ...

Javascript Tool for Generating Typos

My goal with this code was to introduce typos into all words on a page. The script shuffles the letters inside each word, while keeping the first and last characters intact. However, I encountered an issue with punctuation marks such as ".", "(", ",", ")" ...

Issue: Unable to bind function to expression

I'm struggling to understand why this plunker isn't functioning properly. The issue lies in my attempt to bind a basic function from a parent controller to a custom directive within a child element. Surprisingly, using = or < works fine, wher ...

Utilize a generic handler to seamlessly upload files asynchronously

I have implemented the following code to asynchronously upload a file to the server: HTML: <form id="file_upload" action="UploadFile.ashx" target="upload-target" method="post" enctype="multipart/form-data" onsubmit="javascript:return uploadClicked();" ...