slack的chat.postMessage API端点不允许授权标头。

4

我有一段代码在浏览器中运行

<html>

    <script type="module">
        console.log("working");

        var url = "https://slack.com/api/chat.postMessage";
        var auth_token = "xoxb-2B"; //Your Bot's auth token
        var body = {channel: "ses", text: "testing app"}

        async function postData(url = '', data = {}) {
            // Default options are marked with *
            const response = await fetch(url, {
                method: 'POST', // *GET, POST, PUT, DELETE, etc.
                headers: {
                    "Authorization": "Bearer " + auth_token,
                    "Content-Type" : "application/json"
                },
                body: JSON.stringify(data) // body data type must match "Content-Type" header
            });
            return response.json(); // parses JSON response into native JavaScript objects
        }

        postData('https://slack.com/api/chat.postMessage', body)
        .then(data => {
            console.log(data); // JSON data parsed by `data.json()` call
        });
    </script>
</html>

我正在获取访问权限,但是CORS策略阻止了从' http://127.0.0.1:5500 '到'https://slack.com/api/chat.postMessage'的访问请求。预检请求响应中不允许使用请求头字段“authorization”。

我不明白,我需要以某种方式指定令牌,即使在文档中也说要将它放在Authorization标头中,为什么它们不允许?


我认为问题在于您正在从Web浏览器发出请求。 我认为Slack API不支持此操作。 - sandra
1个回答

5

我不明白,我需要以某种方式指定Bearer令牌,即使在文档中说要将其放在授权标头中,为什么他们不允许?

这是一个不同的问题,与Bearer令牌无关。从您收到的错误来看,它意味着您用于获取Slack API的来源没有得到信任(http://127.0.0.1:5500),由服务器定义了授权源的策略,因此浏览器无法做任何事情。(在这里了解更多有关CORS的信息)。

因为我认为Slack不支持这样做,所以您需要从服务器获取Slack API。

解决此问题的一种方法是通过公开后端API,例如:

向Slack发送消息                                                                 Fusebit中运行
router.post('/api/tenant/:tenantId/test', async (ctx) => {
  // Create a Slack client pre-configured with credentials necessary to communicate with your tenant's Slack workspace.
  // For the Slack SDK documentation, see https://slack.dev/node-slack-sdk/web-api.
  const slackClient = await integration.tenant.getSdkByTenant(ctx, connectorName, ctx.params.tenantId);

  // Get the Slack user ID associated with your tenant
  const slackUserId = slackClient.fusebit.credentials.authed_user.id;

  // Send a Direct Message to the Slack user
  const result = await slackClient.chat.postMessage({
    text: 'Hello world!',
    channel: slackUserId,
  });

  console.log('message response', result.message);
  ctx.body = { message: `Successfully sent a message to Slack user ${slackUserId}!` };
});


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接