Here's what I'm trying to do: I have a lambda function triggered by a webhook that will process that data and use it to make a POST request to an api.
I'm using Node.js 12 and the node-fetch module.
Right now the function is being triggered correctly, but it won't send the POST the first time it is called. But if I trigger the lambda function repeatedly in a short amount of time, the requests after the first will get through.
Here's the code in my lambda function's index.js file:
const fetch = require('node-fetch');
exports.handler = async (event) => {
sendPost();
const response = {
statusCode: 200,
body: "Ok",
};
return response;
};
function sendPost() {
const url = "http://requestbin.net/r/vjv4mvvj";
const body = {
foo: "foo",
bar: "bar",
baz: "baz"
};
const params = {
method: "POST",
mode: "cors",
headers: {"Content-Type":"application/json"},
body: JSON.stringify(body)
};
fetch(url, params);
}
When I delete the async in front of (event), then the request goes through the first time, but the server that sends the webhook in the first place doesn't get a response.
So basically I need the POST to send every time the function is called and also be able to return the 200 status code.
I don't have much experience working with async so I know it's related to that, but I'm scratching my head.
The fetch returns a promise, you need an await
. Also you need to mark the sendPost
function as async
. You also need the handler function to wait for sendPost
function to finish.
const fetch = require('node-fetch');
exports.handler = async (event) => {
await sendPost();
const response = {
statusCode: 200,
body: "Ok",
};
return response;
};
async function sendPost() {
const url = "http://requestbin.net/r/vjv4mvvj";
const body = {
foo: "foo",
bar: "bar",
baz: "baz"
};
const params = {
method: "POST",
mode: "cors",
headers: {"Content-Type":"application/json"},
body: JSON.stringify(body)
};
await fetch(url, params);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With