weixin_33697898 2018-07-12 23:40 采纳率: 0%
浏览 47

JavaScript Slack API jQuery

My question is very simple and I thought creating this program would only take a couple hours. However now I have been working on it all day trying to figure out what I could be doing wrong.

All I am trying to do is post messages to slack using their postMessage api. I have been able to send messages succesfully using slacks testing methods.

This is the url that is outputted by the test

https://slack.com/api/chat.postMessage?token=xoxp-xxxxxx-xxxxxxxx-xxxxxxxx-xxxxxxxxxxx&channel=XXXXXXXX&text=Just%20need%20the%20url&as_user=jheuman&pretty=1

I then decided to try it out locally using this html file served from my file system

<!DOCTYPE html>
<html>
<head>
    <title>Testing Slack API</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
    <button onClick="test()">Test</button>
    <button onClick="test2()">Authorization Test</button>

<script>
    function test() {
        var apiUrl = "https://slack.com/api/chat.postMessage";
        var token = "xoxp-xxxxx...";//my token has been omitted for security;
        var channel = "#general";
        var text = "Testing slack api";
        var user = "jheuman";
        var actualToken = "Bearer " + token;


        $.ajax({
            headers: {
                'Authorization':actualToken,
                'Content-Type':'application/json'
            },

            data: JSON.stringify({
                "channel": channel,
                "text": text,
                "as_user": user
            }),
            dataType: 'json',
            processData: false,
            type: 'POST',
            url: apiUrl
        })
        .done(function(data) {
            console.log(JSON.stringify(data));
        })
        .fail(function(response) {
            console.log(JSON.stringify(response));
        });


    };

    function test2() {
        var apiUrl = "https://slack.com/api/auth.test";
        var token = "xoxp-xxxxx..."; //my token has been omitted for security
        var channel = "#general";
        var text = "Testing slack api";
        var user = "jheuman";
        var actualToken = "Bearer" + token;


    $.ajax({
        headers: {
            'Authorization':actualToken
        },
        type: 'POST',
            url: apiUrl,
    })
        .done(function(data) {
        console.log(JSON.stringify(data));
        })
        .fail(function(response) {
        console.log(JSON.stringify(response));
});


    };
</script>

But when I click either button I get the following error:

Failed to load https://slack.com/api/chat.postMessage: Request header field 
Authorization is not allowed by Access-Control-Allow-Headers in preflight 
response. 

So per a friends Suggestion I tried it out on a server. I used Web Server For Chrome to serve it up on port 8887. First without setting cors headers and then with setting cors headers. Both to no avail. I received the same error.

As you can see I also tried the auth.test call but I receive the same error.

Slack specifically states that they prefer an authorization header and that the api can handle json data.

Other things I have tried:

Having no header field with token in data:

data: JSON.stringify({
    'token':actualToken,
    'channel': channel,
    'text': text,
    'as_user': user
}),
dataType: 'json',
processData: false,
type: 'POST',
url: apiUrl

Errors received:

{"ok":false,"error":"invalid_form_data"}

Having no header field with token in data without 'Bearer':

data: JSON.stringify({
    'token':token,
    'channel': channel,
    'text': text,
    'as_user': user
}),
dataType: 'json',
processData: false,
type: 'POST',
url: apiUrl

Errors received:

{"ok":false,"error":"invalid_form_data"}

Things I have looked into but don't think will effect outcome

The type of token

So how do I get this post request to work?

I am not set on jquery or ajax, it is just what I have used in the past so if you have a different request library to use I'm all ears.

If you need more information I will try to give it to you

  • 写回答

2条回答 默认 最新

  • weixin_33739541 2018-07-13 00:43
    关注

    You need to reply to that CORS preflight with the appropriate CORS headers to make this work. One of which is indeed Access-Control-Allow-Headers. That header needs to contain the same values the Access-Control-Request-Headers header contained (or more).

    https://fetch.spec.whatwg.org/#http-cors-protocol explains this setup in more detail.

    headers: {
                    'Authorization':actualToken,
                    'Content-Type':'application/json',
                    'Access-Control-Allow-Headers':'x-requested-with'
                },
    
    评论

报告相同问题?

悬赏问题

  • ¥15 Coze智能助手搭建过程中的问题请教
  • ¥15 12864只亮屏 不显示汉字
  • ¥20 三极管1000倍放大电路
  • ¥15 vscode报错如何解决
  • ¥15 前端vue CryptoJS Aes CBC加密后端java解密
  • ¥15 python随机森林对两个excel表格读取,shap报错
  • ¥15 基于STM32心率血氧监测(OLED显示)相关代码运行成功后烧录成功OLED显示屏不显示的原因是什么
  • ¥100 X轴为分离变量(因子变量),如何控制X轴每个分类变量的长度。
  • ¥30 求给定范围的全体素数p的(p-2)/p的连乘积值
  • ¥15 VFP如何使用阿里TTS实现文字转语音?