使用react js调用webhook

问题描述 投票:0回答:1

大家好,有没有办法使用 React js 从回发 webhook 获取响应?

如果是的话,可以举个例子吗?

问候!

reactjs webhooks
1个回答
0
投票

是的,您可以在 React JS 应用程序中调用 Webhook 并处理其响应。在 React 中,您可以使用 JavaScript 的 fetch API 或 Axios 等库来发出 HTTP 请求。下面是在 React 组件中使用 fetch API 的基本示例。此示例假设您正在向 webhook 发出 POST 请求并期待 JSON 响应:

import React, { useState } from 'react';

function WebhookComponent() {
    const [webhookResponse, setWebhookResponse] = useState(null);

    const callWebhook = async () => {
        try {
            const response = await fetch('actual URL of the webhook', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ key: 'value' }),
            });

            if (!response.ok) {
                throw new Error('Network response was not ok');
            }

            const data = await response.json();
            setWebhookResponse(data);
        } catch (error) {
            console.error('Error fetching data: ', error);
            setWebhookResponse(null);
        }
    };

    return (
        <div>
            <button onClick={callWebhook}>Call Webhook</button>
            {webhookResponse && <div>Response: {JSON.stringify(webhookResponse)}</div>}
        </div>
    );
}

export default WebhookComponent;
© www.soinside.com 2019 - 2024. All rights reserved.