首页 > 解决方案 > JavaScript 松弛 api jquery

问题描述

我的问题很简单,我认为创建这个程序只需要几个小时。但是现在我整天都在努力试图找出我可能做错了什么。

我要做的就是使用他们的postMessage api将消息发布到 slack 。我已经能够使用松弛测试方法成功发送消息。

这是测试输出的url

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

然后我决定使用从我的文件系统提供的这个 html 文件在本地试用它

<!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>

但是,当我单击任一按钮时,都会出现以下错误:

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

因此,根据朋友的建议,我在服务器上进行了尝试。我使用Web Server For Chrome在端口 8887 上提供服务。首先不设置 cors 标头,然后设置 cors 标头。两者都无济于事。我收到了同样的错误。

正如你所看到的,我也尝试了 auth.test 调用,但我收到了同样的错误。

Slack 特别声明他们更喜欢授权标头,并且 api 可以处理 json 数据。

我尝试过的其他事情:

数据中没有带有令牌的标头字段:

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

收到的错误:

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

在没有“Bearer”的数据中没有带有令牌的标头字段:

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

收到的错误:

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

我研究过但认为不会影响结果的事情

令牌类型

那么如何让这个帖子请求起作用呢?

我没有设置 jquery 或 ajax,这正是我过去使用的,所以如果你有不同的请求库要使用,我会全力以赴。

如果您需要更多信息,我会尽力提供给您

标签: javascriptjqueryajaxslack-api

解决方案


由于正确配置 CORS 以发送具有内容类型的数据application/json可能很棘手,因此我建议将请求发送application/x-www-form-urlencoded为 AJAX 的默认设置。

例子:

var apiUrl = "https://slack.com/api/chat.postMessage";
var token = MY_TOKEN;
var channel = "general";
var text = "Testing slack api";
var user = "jheuman";

 $.ajax({                   
    data: {
        "token": token,
        "channel": channel,
        "text": text,
        "as_user": user
    },                      
    dataType: 'text',
    type: 'POST',           
    url: apiUrl,
    error: function(xhr,status,error){              
        console.log("error: " + error);
    },
    success: function(data) {
        console.log("result: " + data);
    }
});

如果您遇到 CORS 错误,您可以添加crossDomain: true

此解决方案在普通浏览器中运行时经过测试和工作。


推荐阅读