0

I have a stage in AWS API Gateway that takes POST requests. If I call this API Gateway with Postman, everything works as expected. I can see in CloudWatch logs, that the body of the POST is present. The body is as follows (shortened):

{
    "Success": "1",
    "Item": {
        "IngameName": "SomeName",
        "Timestamp": "Mon Oct 12 2020 19:07:29 GMT+0100 (British Summer Time)"
    }
}

I also set a header for the content type in Postman: Content-Type : application/json.

I try to make the same call again using fetch in JavaScript:

let testJson = {
    "Success": "1",
    "Item": {
        "IngameName": "SomeName",
        "Timestamp": "Mon Oct 12 2020 19:07:29 GMT+0100 (British Summer Time)"
    }
};
fetch(apiGatewayAddressLocal, {
    method: 'POST',
    body: JSON.stringify(testJson),
    headers: {
        'Content-Type': 'application/json'
    }
});

The fetch call reaches API Gateway successfully, but CloudWatch logs say that the body is empty. I have also tried doing json.parse instead of json.stringify but this gives me Unexpected token errors in the console. I saw some solutions including Accept:application/json as a header, which I tried but does not fix the solution. I also tried the solution suggested here, but then I could not reach API Gateway at all.

I have double checked that apiGatewayAddressLocal definitely contains a valid link, it is the same as I used in Postman

Why is my fetch call not passing any body to API Gateway?

August Williams
  • 907
  • 4
  • 20
  • 37

1 Answers1

0

This problem was happening because the fetch command was not included inside an async function, and the fetch command needed to be used with await. I also added in a no-cors mode with the fetch operation.

async function someFunction(callback) {
    let testJson = {
        "Success": "1",
        "Item": {
            "IngameName": "SomeName",
            "Timestamp": "Mon Oct 12 2020 19:07:29 GMT+0100 (British Summer Time)"
        }
    };
    await fetch(apiGatewayAddressLocal, {
        method: 'POST',
        mode: 'no-cors',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(testJson)
    });
    callback();
}
August Williams
  • 907
  • 4
  • 20
  • 37