我试图理解一个异步函数,将其转换为用例的同步类型,
该函数正在使用 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();
}
Run Code Online (Sandbox Code Playgroud)
我想知道
options是否是原始请求帖子正文?
或者options仅用于构造端点和标头?
我的理解是否正确,没有 Post 请求正文,
而只有 httpsendpoint和headers?
小智 5
使用 Node.js POST 到 Slack 的示例(使用 axios)
你应该能够用 axios 完成同样的事情,比如......
'use strict';
const axios = require('axios').default;
const main = async () => {
try {
const data = 'Hello World ! ';
const payload = {
attachments: [{text: data, color: 'green'}]
};
const options = {
method: 'post',
baseURL: 'https://hooks.slack.com/services/xxxxxxxxxxxxx',
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
},
data: payload
};
await axios.request(options);
} catch (e) {
const status = e.response.status;
console.error(`There was an error, HTTP status code: ${status}`);
}
}
}
main();
Run Code Online (Sandbox Code Playgroud)