skip to Main Content

I am a newer with AWS Lambda function to expect response an simple array like this:

I have setup a simple Lambda Node function SimpleArray:

export const handler = async (event) => {
  const responseArray = [
    { name: "Item 1", value: 100 },
    { name: "Item 2", value: 200 },
    { name: "Item 3", value: 300 }
  ];
  
  return {
    statusCode: 200,
    body: JSON.stringify(responseArray)
  };
};

In my Javascript client, i consume api by using fetch:

fetch(`${APP_ROOT_API_URL}/SimpleArray`, {
    mode: "no-cors",
    method: "POST",
    headers: {
        Accept: "application/json",
        "Content-Type": "application/json",
    },
})
.then((resp) => resp.json())
.then(console.log)

I see the response is already there in Network tab

Response

But i received an error in console:

Error

I tried to change it using resp.text()

fetch(`${APP_ROOT_API_URL}/SimpleArray`, {
    mode: "no-cors",
    method: "POST",
    headers: {
        Accept: "application/json",
        "Content-Type": "application/json",
    },
})
.then((resp) => resp.json())
.then(console.log)

But what i received is a Blank text: ""

2

Answers


  1. It looks like you are on the right track with your Lambda function and fetch setup. However, there are a couple of things you might need to adjust in order to properly receive the JSON response from your Lambda function.

    1. CORS Mode: In your fetch request, you’ve set mode: "no-cors". This mode restricts the information returned by the response. To receive the JSON data, you need to remove this line or set it to mode: "cors" if your Lambda function’s API allows CORS.

    2. Response Handling: You are using .json() to parse the response, which is the correct approach. The issue might be related to the headers or CORS configuration.

    Here’s an updated version of your fetch code:

    fetch(`${APP_ROOT_API_URL}/SimpleArray`, {
        method: "POST",
        headers: {
            Accept: "application/json",
            "Content-Type": "application/json",
        },
    })
    .then((resp) => {
        if (!resp.ok) {
            throw new Error("Network response was not ok");
        }
        return resp.json();
    })
    .then((data) => {
        console.log(data);
    })
    .catch((error) => {
        console.error("Fetch error:", error);
    });
    

    Updated handler:

    export const handler = async (event) => {
      try {
        const responseArray = [
          { name: "Item 1", value: 100 },
          { name: "Item 2", value: 200 },
          { name: "Item 3", value: 300 }
        ];
    
        return {
          statusCode: 200,
          headers: {
            "Access-Control-Allow-Headers": "Authorization, Content-Type",
            "Access-Control-Allow-Origin": "*",
            "Access-Control-Allow-Methods": "POST, OPTIONS"
          },
          body: JSON.stringify(responseArray)
        };
      } catch (error) {
        return {
          statusCode: 500,
          headers: {
            "Access-Control-Allow-Headers": "Authorization, Content-Type",
            "Access-Control-Allow-Origin": "*",
            "Access-Control-Allow-Methods": "POST, OPTIONS"
          },
          body: error
        };
      }
    
    };
    

    A couple of things to note:

    • I’ve added an error handling mechanism using .catch() to catch any network-related errors.
    • I’ve also added a check using if (!resp.ok) to handle cases where the response is not successful (e.g., non-200 status codes).

    Make sure that your Lambda function’s API has the necessary CORS configuration to allow your JavaScript client to make requests to it. This often involves setting appropriate headers in your Lambda function’s response to handle cross-origin requests.

    If you still encounter issues, double-check your Lambda function’s logs for any errors or additional information that might help diagnose the problem.

    Login or Signup to reply.
  2. Your lambda function looks fine. The issue might because you haven’t enabled CORS in API Gateway.

    Step 1: Adjust your client request:

    • Remove mode: "no-cors" in your client request
    • Add headers: { "Access-Control-Allow-Origin": "*" } to your request. And do 2 steps below:

    Step 2: You need to enable CORS in API Gateway:

    Go to API Gateway => CORS, set up:

    1. Access-Control-Allow-Origin: *
    2. Access-Control-Allow-Methods: *
    3. Access-Control-Allow-Headers: *

    Step 3: Add route with method OPTIONS:

    Go to API Gateway => Routes, create your same api route with OPTIONS method

    Done. Hope it helps

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search