AWS S3 bucket error in Fetching AWS gateway API

0

I have a simple API that works in my browser through the url:

https://XXX.execute-api.us-east-2.amazonaws.com/testing/calculator?x=test&y=testing

I get a 200 response there.

The problem is when I try to take 2 inputs from an HTML page then pass them into the API to get the response and display the data on the html page I get an error saying: An error occured: Load failed

It could be something to do with CORS or something within my JavaScript. I am new to AWS and JS so I have been asking chatGPT for help along the way.

Below is my javascript:

    document.addEventListener('DOMContentLoaded', function() {
        const calculateButton = document.getElementById('calculate-button');
        const resultDiv = document.getElementById('result');
    
        calculateButton.addEventListener('click', function() {
            // Retrieve the values of x and y from the input fields
            const x = parseFloat(document.getElementById('x').value);
            const y = parseFloat(document.getElementById('y').value);
    
            // Check if x and y are valid numbers
            if (isNaN(x) || isNaN(y)) {
                resultDiv.textContent = 'Please enter valid numbers for x and y.';
                return;
            }
    
            // Make a GET request to your Lambda function with x and y as query parameters
            fetch(`https://XXXX.execute-api.us-east-2.amazonaws.com/testing/calculator?x=${x}&y=${y}`)
                .then(response => {
                    if (!response.ok) {
                        throw new Error('Network response was not ok');
                    }
                    return response.json();
                })
                .then(data => {
                    // Handle the response data as needed
                    resultDiv.textContent = `Result: ${data.result}`;
                })
                .catch(error => {
                    resultDiv.textContent = `An error occurred: ${error.message}`;
                    console.error(error);
                });
        });
    });

Could someone help me out with this issue?

I also am attaching my CORS settings for API gateway CORS Settings

1 Answer
0

Hello.

Even if CORS settings are completed on API Gateway, I think an error will occur if the CORS header is not returned in the Lambda response.
For example, you can add headers to the response using Lambda code as shown below.

exports.handler = async (event) => {
    const response = {
        statusCode: 200,
        headers: {
            "Access-Control-Allow-Headers" : "Content-Type",
            "Access-Control-Allow-Origin": "*",
            "Access-Control-Allow-Methods": "GET"
        },
        'body': JSON.stringify({
            message: 'hello world Test2!!',
        })
    };
    return response;
};

If CORS is the issue, the troubleshooting documentation below may be helpful.
https://repost.aws/knowledge-center/api-gateway-cors-errors

profile picture
EXPERT
answered 9 months ago
  • Hi, Thanks for the answer!

    This is what my lambda code looks like (python): Could you indicate the best way to incorporate that into my header? import json

    def lambda_handler(event, context): x = event['queryStringParameters']['x'] y = event['queryStringParameters']['y']

    print(f" x:{x} , y:{y}")
    
    
    res_body = {}
    res_body['x'] = str(x)
    res_body['y'] = str(y)
    res_body['ans'] = add(x,y)
    
    http_res = {}
    http_res['statusCode'] = 200
    http_res['headers'] = {}
    http_res['headers']['Content-Type'] = 'application/json'
    http_res['body'] = json.dumps(res_body)
    
    return http_res
    

    def add(x,y): return x+y

  • I think it's okay if you include it in the header like below.

    import json
    
    def lambda_handler(event, context):
        x = event['queryStringParameters']['x']
        y = event['queryStringParameters']['y']
    
        print(f" x:{x} , y:{y}")
    
    
        res_body = {}
        res_body['x'] = str(x)
        res_body['y'] = str(y)
        res_body['ans'] = add(x,y)
    
        http_res = {}
        http_res['statusCode'] = 200
        http_res['headers'] = {
            "Content-Type": "application/json",
            "Access-Control-Allow-Headers": "Content-Type",
            "Access-Control-Allow-Origin": "*",
            "Access-Control-Allow-Methods": "GET"
        }
        http_res['body'] = json.dumps(res_body)
    
        return http_res
    def add(x,y):
        return x+y
    

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.

Guidelines for Answering Questions