call a webhook in javascript

To call a webhook in JavaScript, we can use the fetch function to send an HTTP request to the webhook URL. Here's an example code snippet that shows how to do this:

index.tsx
async function callWebhook(webhookUrl, payload) {
  const response = await fetch(webhookUrl, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(payload),
  });
  
  if (!response.ok) {
    throw new Error(`Failed to call webhook: ${response.status} ${response.statusText}`);
  }
}
341 chars
14 lines

In the code above, we define an asynchronous function called callWebhook which takes two arguments: the URL of the webhook and the payload to send. Inside the function, we use the fetch function to send a POST request to the webhook URL, with the payload included in the request body as a JSON string.

If the HTTP response is not successful (i.e., the status code is not in the 200-299 range), we throw an error with a message indicating the reason for the failure.

To use this function, simply call it with the webhook URL and payload you want to send:

index.tsx
const webhookUrl = 'https://example.com/my-webhook';
const payload = {
  event: 'user.created',
  user_id: '123456',
  name: 'John Smith',
};

callWebhook(webhookUrl, payload)
  .then(() => console.log('Webhook called successfully'))
  .catch(error => console.error(`Failed to call webhook: ${error.message}`));
312 chars
11 lines

In the example above, we define the webhook URL and payload to send, then call the callWebhook function with those parameters. We use a .then callback to log a success message when the webhook call completes successfully, and a .catch callback to handle any errors that may occur.

gistlibby LogSnag