Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CORS error while trying to post data with Axios on AWS REST API configuration using a node.js Lambda function

I'm posting data to a DynamoDB table with axios in a React front-end. The API is set up through a serverless configuration with an API Gateway and Lambda on AWS.

While the request goes through and I see the added item on the database I still get a CORS error https://i.sstatic.net/m7yMG.jpg

This is the axios method:

import axios from "axios";

export const sendItemToDB = async (_data) => {
    if (!_data) { return };
    try {
        const res = await axios({
            method: "POST",
            url: process.env.REACT_APP_QUERY_API,
            data: _data,
            headers: {
                "Content-Type": "text/plain"
            },
        });
        console.log("data returned from api", res);
    } catch (error) {
        console.log("Error sending File to db: ");
        console.log(error);
    }
};

And the API method on Lambda:

const createRecord = async (event) => {
    const response = { statusCode: 200 };

    try {
        const body = JSON.parse(event.body);
        const params = {
            TableName: process.env.DYNAMODB_TABLE_NAME,
            Item: marshall(body || {}),
        };
        const createResult = await db.send(new PutItemCommand(params));
        response.body = JSON.stringify({
            message: "Successfully created record.",
            createResult,
        });
    } catch (e) {
        console.error(e);
        response.statusCode = 500;
        response.body = JSON.stringify({
            message: "Failed to create record.",
            errorMsg: e.message,
            errorStack: e.stack,
        });
    }

    return response;
};

I based this configuration on this tutorial : https://github.com/jacksonyuan-yt/dynamodb-crud-api-gateway

like image 466
Stavros K Avatar asked Sep 14 '26 13:09

Stavros K


2 Answers

I solved this following amazon documentation and reconfiguring the serveless deployment yml.
Serverless documentation on api gateway and lambda proxy integration here

Adding the missing headers to all lambda functions was essential.

const response = {
        statusCode: 200,
        headers: {
            "Access-Control-Allow-Headers" : "Content-Type",
            "Access-Control-Allow-Origin": "*",
            "Access-Control-Allow-Methods": "OPTIONS,POST,GET"
        },
    };

Also testing that OPTIONS is working for the preflight: https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-test-cors.html

like image 164
Stavros K Avatar answered Sep 17 '26 12:09

Stavros K


Just as Stavros noticed, the problem is that this is not a simple cross-origin POST method request (because it contains custom headers), so you need to tweak CORS settings of AWS API Gateway by adding

  • "POST, GET & OPTIONS" for Access-Control-Allow-Methods
  • "content-type" for Access-Control-Allow-Headers

You can do it through console like this

enter image description here

You also might need to add those headers in lambda like this enter image description here and it will work.

like image 20
MegaMilivoje Avatar answered Sep 17 '26 12:09

MegaMilivoje