如何使用使用axios的NodeJ将数据发布到Slack?

问题描述 投票:0回答:1

我正在尝试了解异步功能,将其转换为用例的同步类型,该函数正在使用Node的https模块向Slack发出Post请求,我希望将此代码转换为使用axios库。

我无法理解将邮寄主体发送到端点的确切含义。

功能代码如下-

function postToSlack(logTitle, logMessage, logType, context) {
    var payloadStr = JSON.stringify({
        'username': slackBotUsername,
        'attachments': [
            {
                'title': logTitle,
                'fallback': logMessage,
                'text': logMessage,
                'color': getLogTypeColour(logType)
            }
        ],
        'icon_emoji': slackBotIconEmoji,
    });

    var options = {
        hostname: 'hooks.slack.com',
        port: 443,
        path: slackPostPath,
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Content-Length': Buffer.byteLength(payloadStr),
        }
    };

    var postReq = https.request(options, function(res) {
        var chunks = [];
        res.setEncoding('utf8');
        res.on('data', function(chunk) {
            return chunks.push(chunk);
        });
        res.on('end', function() {
            var body = chunks.join('');

            if (res.statusCode < 400) {
                console.info('Message posted successfully');
            } else if (res.statusCode < 500) {
                console.error("Error posting message to Slack API: " + res.statusCode + " - " + res.statusMessage);
            } else {
                console.error("Server error when processing message: " + res.statusCode + " - " + res.statusMessage);
            }

            if (completedRequests++ == totalRequests - 1) {
                context.succeed('DONE');
            }
        });
        return res;
    });

    postReq.write(payloadStr);
    postReq.end();
}

我想知道,options是原始请求发布主体吗?,还是options仅用于构造endpointheaders

我的理解是正确的,没有发布请求正文,但是只是一个https endpointheaders

参考-https://flaviocopes.com/node-http-post/

node.js slack
1个回答
0
投票

payloadStr

© www.soinside.com 2019 - 2024. All rights reserved.