【问题标题】:CORS error while trying to post data with Axios on AWS REST API configuration using a node.js Lambda functionCORS error while trying to post data with Axios on AWS REST API configuration using a node.js Lambda function
【发布时间】:2022-12-19 03:35:29
【问题描述】:

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.stack.imgur.com/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

【问题讨论】:

    标签: reactjs amazon-web-services aws-lambda axios aws-api-gateway


    【解决方案1】:

    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

    【讨论】:

      【解决方案2】:

      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 tweakCORS settingsofAWS API Gatewayby adding

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

      You can do it through console like this

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

      【讨论】:

        猜你喜欢
        • 2022-12-26
        • 2022-12-01
        • 2018-12-13
        • 2022-11-09
        • 2018-05-17
        • 2023-02-09
        • 1970-01-01
        • 2023-02-13
        • 1970-01-01
        相关资源
        最近更新 更多