I have a front-end and a backend where I am setting up for the first time AWS lambda functions. However, from my frontend POST request, I receive null data in the body.
As I understand, it is sending OPTIONS first to validate the headers, and after that should send the POST request. But this isn’t happening. I am unsure if the order should be happening under the hood.
Any help will be appreciated.
Frontend req:
const sendConfig = async () => {
const url = 'http://127.0.0.1:3000/api/data/config'; // TODO: change to real env api url
try {
const response = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(configuration),
mode: 'cors'
});
if (!response.ok) {
throw new Error('Failed to send configuration');
}
const result = await response.json();
console.log("Config: ", result);
} catch (error) {
console.log('Error:', error.message);
}
};
Backend:
module.exports.configDataHandler = async (event, context) => {
if (event.httpMethod === 'OPTIONS') {
console.log("event: ", event)
return {
statusCode: 200,
headers: {
'Access-Control-Allow-Origin': 'http://localhost:3000', // Substitua pela origem correta
'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type, Authorization',
},
body: null
};
}
try {
console.log("Received event: ", event);
const body = JSON.parse(event.body);
console.log("Received config: ", body);
return {
statusCode: 200,
body: JSON.stringify({ message: 'Received config:', body })
};
}
catch (error) {
console.error('Error processing request:', error);
return {
statusCode: 500,
body: JSON.stringify({ message: error.message })
};
}
};
Lambda:
ConfigFunction:
Type: AWS::Serverless::Function
Properties:
Handler: server.configDataHandler
Runtime: nodejs18.x
CodeUri: .
Timeout: 60
Environment:
Variables:
NODE_ENV: dev
Events:
DataApi:
Type: Api
Properties:
Path: /api/data/config
Method: any