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.