【问题标题】:slack chat.postMessage API endpoint is not allowing the authorization headerslack chat.postMessage API 端点不允许授权标头
【发布时间】:2022-01-18 07:28:12
【问题描述】:

我在浏览器中运行了这段代码

<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”获取:请求标头字段授权不允许预检响应中的 Access-Control-Allow-Headers。

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

【问题讨论】:

  • 我认为问题在于您是从网络浏览器发出请求。我认为 Slack API 不支持。

标签: javascript fetch-api slack-api


【解决方案1】:

我不明白,我需要以某种方式指定不记名令牌,甚至 在文档中说要把它放在授权标头中,为什么不 他们允许吗?

这是一个不同的问题,与 Bearer 令牌完全无关。 根据您收到的错误,这意味着您用于获取 Slack API 的来源不受信任(http://127.0.0.1:5500),您无法从浏览器中执行任何操作,因为这是来自定义授权来源的服务器。 (Learn more about CORS here) 由于我认为 Slack 不支持此功能,因此您需要从服务器获取 Slack API。

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

Post a message to Slack                                                                                 Run in 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}!` };
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-04-28
    • 1970-01-01
    • 1970-01-01
    • 2019-08-19
    • 2020-02-03
    • 1970-01-01
    • 1970-01-01
    • 2017-02-04
    相关资源
    最近更新 更多