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
But i received an error in console:
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
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.
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 tomode: "cors"
if your Lambda function’s API allows CORS.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:
Updated handler:
A couple of things to note:
.catch()
to catch any network-related errors.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.
Your lambda function looks fine. The issue might because you haven’t enabled CORS in API Gateway.
Step 1: Adjust your client request:
mode: "no-cors"
in your client requestheaders: { "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:
Access-Control-Allow-Origin
:*
Access-Control-Allow-Methods
:*
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