React app error when calling API endpoint

30 Views Asked by At

I am calling a small react component from my AWS Application Loader Balancer. What this react app does is, on click of a button, I calls an API endpoint from where a small lambda code executes AWS batch job. So the route for this: ALB-->API endpoint-->Lambda function-->AWS Batch

I've setup the necessary infrastructure for ALB,API,Lambda function etc. When I visit my ALB DNS, I am seeing my react code there (with a button).On click of the button, it seems to call the API GW correctly thereby executing the lambda function successfully. I can also see the AWS Batch job triggered successfully.

Now the problem happens somewhere in the code where it throws the error "Error during fetch" that seems to be originating from the react code. This error is visible in the UI "Error: Network error: ${response.status} - ${response.statusText}". But as I mentioned earlier, the API calling is successful. Its just the response that is not shown correctly in the UI.

I am unable to figure this out after so many tries.

My lambda code is:

const { BatchClient, SubmitJobCommand } = require("@aws-sdk/client-batch"); // CommonJS import
const config = {
         region: "us-east-1",
    };

const batchClient = new BatchClient(config);

exports.handler = async(event, context) => {
const params = {
 jobDefinition: "dev-poc-dtx-infra-dtx-login-test",
 jobName: "test-treasury-poc",
 jobQueue: "dev-poc-dtx-infra-jq-alpha",
};

try {
    const command = new SubmitJobCommand(params);
    const data = await batchClient.send(command);
    console.log('Job Submitted successfully...', data);
    return {
        statusCode: 200,
        headers: {
          "Access-Control-Allow-Origin": "*",
          "Access-Control-Allow-Methods": "GET,POST,PUT,DELETE,OPTIONS",
          "Access-Control-Allow-Headers": "Content-Type,X-Amz-Date,Authorization,X-Api-Key,X- 
Amz-Security-Token"
        },
        body: JSON.stringify('Job submitted -> ok'),
    };
} catch(error) {
    console.error('Error starting batch job: ', error);
    return {
        statusCode: 500,
        body: JSON.stringify('Error submitting job: ', error),
    };
  }
};

My react code is:

import React, {useState, useEffect} from 'react';

const API_ENDPOINT = "https://g5h674xx12.execute-api.us-east-1.amazonaws.com/test/batch";
const CallApiButton = () => {
const [apiResponse, setApiResponse] = useState('');
const [successMessage, setSuccessMessage] = useState('');
const [errorMessage, setErrorMessage] = useState('');

const callApi = async () => {
    try {
        const headers = {
            "Content-Type": 'application/json',
            "Access-Control-Allow-Headers" : "*",
            "Access-Control-Allow-Origin" : '*',
            "Access-Control-Allow-Methods" : '*',
        };
        const response = await fetch(API_ENDPOINT, {
            mode: 'no-cors',
            method: 'GET',
            statusCode: 200,
            headers: headers,
        });
        if(response.ok) {
           const responseData = await response.json();
           setApiResponse(responseData);
           setSuccessMessage('Success');
           setErrorMessage('');
        } else {
            throw new Error(`Network response not ok: ${response.status} - 
${response.statusText}`);
        }
       } catch(error){
           console.error('Error during fetch', error);
           setSuccessMessage('');
           setErrorMessage(error.message);
       }
     };

return (
    <div>
      <button onClick={callApi}>Trigger Lambda function</button>
      {/* Add any other UI elements as needed */}
      {successMessage && <p>{successMessage}</p>}
      {errorMessage && <p>Error: {errorMessage}</p>}
      {apiResponse && (
        <div>
            <h2>API Response:</h2>
            <pre>{JSON.stringify(apiResponse, null, 2)}</pre>
        </div>
      )}
    </div>
  );
};

export default CallApiButton;

After invoking the ALB DNS and pressing the button, it goes into the catch part and shows the error message from there (Although it is successfully calling the API endpoint).

I have a related post here

Not sure what might be wrong here? I am expecting to see the 'Sucess' message printed in the UI instead of the error message from the catch block.

Any help in solving this issue much appreciated.

0

There are 0 best solutions below