大家好,有没有办法使用 React js 从回发 webhook 获取响应?
如果是的话,可以举个例子吗?
问候!
是的,您可以在 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;