CoffeeScript:HTTPS发布到API,处理响应

时间:2018-06-02 21:00:20

标签: javascript post coffeescript http-post hubot

我是CoffeeScript / JavaScript的新手,但为Hubot编写了一个脚本,以便与Coffee中的Ansible Tower API对话。以下是我目前的代码:

module.exports = (robot) ->
robot.respond /deploy zabbix agent (.*)/i, (res) ->
    host = res.match[1]

    https = require 'https'

    authbody = JSON.stringify({
        username: "awx.api",
        password: "example"
    })

    authrequest = new https.ClientRequest({
        hostname: "awx.example.co.uk",
        port: 443,
        path: "/api/v2/authtoken/",
        method: "POST",
        headers: {
            "Content-Type": "application/json",
            "Content-Length": Buffer.byteLength(body)
        }
    })

    authrequest.end(authbody)

    body = JSON.stringify({
        limit: "#{host}"
    })

    request = new https.ClientRequest({
        hostname: "awx.example.co.uk",
        port: 443,
        path: "/api/v2/job_templates/35/launch/",
        method: "POST",
        headers: {
            "Content-Type": "application/json",
            "Content-Length": Buffer.byteLength(body)
        }
    })

    request.end(body)

    res.reply "Deploying zabbix agent to #{host}"

authrequest 部分,我将我的用户名和密码发布到API,它应该以以下格式返回响应JSON:

{
"token": "8f17825cf08a7efea124f2638f3896f6637f8745",
"expires": "2013-09-05T21:46:35.729Z"
}

我的问题是我如何存储令牌以在后来的请求中用作我的身份验证。

1 个答案:

答案 0 :(得分:0)

您可以将其存储在localStorage中,如下所示:

localStorage.setItem("token", "8f17825cf08a7efea124f2638f3896f6637f8745",);

并在您提出请求并插入标题时获取

const token = JSON.parse(localStorage.getItem('token'));

request = new https.ClientRequest({
    hostname: "awx.example.co.uk",
    port: 443,
    path: "/api/v2/job_templates/35/launch/",
    method: "POST",
    headers: {
        "Content-Type": "application/json",
        "Content-Length": Buffer.byteLength(body),
        'Authorization': 'Bearer ' + token
    }
})
request.on('response', function (response) {
  response.on('data', function (chunk) {
       let json = JSON.parse(chunk);
       localStorage.setItem("token", json['token']);
  });
});