为什么我必须手动转义我的引号才能使用 http.request. 编写方法来发送 JSON

  • 本文关键字:request http 方法 JSON 转义 node.js slack
  • 更新时间 :
  • 英文 :


执行以下代码时,我可以让request.write()工作的唯一方法是手动转义引号。我试图在传递之前JSON.stringify()论点,但这仍然不起作用。

关于这里发生了什么以及如何解决它的任何想法?

我已经尝试了JSON.stringify(message)以及其他许多方法。我也打算通过香草https.request来做到这一点。

function samplePost(responseURL){
let postOptions = {
method: 'POST',
headers: {
'Content-Type': 'application/json'
}
};
let request = https.request(responseURL, postOptions, (res) => {
let rawData = '';
res.on('data', (chunk) => { rawData += chunk; });
res.on("end",() => {
//console.log(rawData);
});
});
//can't seem to send this along properly unless I escape all quotations
//example "{ "text": "Testing this message out once again..." }"
let message = [
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": "Are you sure you want to invite to :video_game:?n*" + email + "* on *" + platform + "*"
}
},
{
"type": "actions",
"elements": [
{
"type": "button",
"text": {
"type": "plain_text",
"emoji": true,
"text": "Invite"
},
"value": "invite"
},
{
"type": "button",
"text": {
"type": "plain_text",
"emoji": true,
"text": "No"
},
"value": "dont_invite"
}
]
}
];
request.write(message);
request.end();
}

上面的代码与松弛集成。

我希望 slack 在发送时输出我的消息request.write(message)

相反,我留下的是一个空白的回复。好像什么都没有出错,但也没有发送任何数据。

事实证明,这是我如何将返回消息格式化为 slack 的简单问题。

我需要确保我的松弛块首先被添加到一个 json 对象中,并将"块"作为我的块所在的键。其次,我需要在发送之前对 json 进行 JSON.string化。见下文。

function samplePost(responseURL){
let postOptions = {
method: 'POST',
headers: {
'Content-Type': 'application/json'
}
};
let request = https.request(responseURL, postOptions, (res) => {
let rawData = '';
res.on('data', (chunk) => { rawData += chunk; });
res.on("end", () => { });
});
let messageBlocks = [
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": "Are you sure you want to invite to :video_game:?n*" + email + "* on *" + platform + "*"
}
},
{
"type": "actions",
"elements": [
{
"type": "button",
"text": {
"type": "plain_text",
"emoji": true,
"text": "Invite"
},
"value": "invite"
},
{
"type": "button",
"text": {
"type": "plain_text",
"emoji": true,
"text": "No"
},
"value": "dont_invite"
}
]
}
];
//ADDED THIS
let returnMessage = {
"blocks": messageBlocks
}
request.write(JSON.stringify(messageBlocks));
request.end();
}

最新更新