【问题标题】:CoffeeScript: HTTPS Post to API, handle responseCoffeeScript:HTTPS 发布到 API,处理响应
【发布时间】:2018-11-12 15:22:05
【问题描述】:

我是 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"
}

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

【问题讨论】:

    标签: javascript post coffeescript http-post hubot


    【解决方案1】:

    你可以像这样将它存储在 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']);
      });
    });
    

    【讨论】:

    • 如何通过 authrequest 位从响应中获取这些内容?
    猜你喜欢
    • 2010-10-03
    • 1970-01-01
    • 1970-01-01
    • 2017-09-28
    • 2023-03-30
    • 2017-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多