【问题标题】:Create reusable http request Node.js function创建可重用的 http 请求 Node.js 函数
【发布时间】:2016-08-02 21:06:54
【问题描述】:

我正在尝试创建一个脚本来触发 IFTTT 通知。 到目前为止我的工作是:

var http = require('http')

var body = JSON.stringify({
    value1: "Temp Humid Sensor",
    value2: "Error",
    value3: "reading measurements"
})


var sendIftttTNotification = new http.ClientRequest({
    hostname: "maker.ifttt.com",
    port: 80,
    path: "/trigger/th01_sensor_error/with/key/KEY",
    method: "POST",
    headers: {
        "Content-Type": "application/json",
        "Content-Length": Buffer.byteLength(body)
    }
})

sendIftttTNotification.end(body)

但我想做的是创建一个可重用的函数,这样我就可以在不同的情况下用不同的参数调用它。

到目前为止我想出了什么:

var http = require('http')

function makeCall (body, callback) {
    new http.ClientRequest({
    hostname: "maker.ifttt.com",
    port: 80,
    path: "/trigger/th01_sensor_error/with/key/UMT-x9TH83Kzcq035sh9B",
    method: "POST",
    headers: {
        "Content-Type": "application/json",
        "Content-Length": Buffer.byteLength(body)
    }
}

var body1 = JSON.stringify({
    value1: "Sensor",
    value2: "Error",
    value3: "reading measurements"
})

makeCall(body1);

var body2 = JSON.stringify({
    value1: "Sensor",
    value2: "Warning",
    value3: "low battery"
})

makeCall(body2);

但是什么也没发生,我在终端运行时没有收到任何错误:“node script.js”

有人可以帮我解决这个问题吗?

谢谢!

【问题讨论】:

    标签: node.js function http httprequest


    【解决方案1】:

    您的函数正在发出请求但未发送。

    试试这个:

    function makeCall (body, callback) {
        var request = new http.ClientRequest({
        hostname: "maker.ifttt.com",
        port: 80,
        path: "/trigger/th01_sensor_error/with/key/UMT-x9TH83Kzcq035sh9B",
        method: "POST",
        headers: {
            "Content-Type": "application/json",
            "Content-Length": Buffer.byteLength(body)
        });
        request.end(body);
        callback();
    }
    

    【讨论】:

      猜你喜欢
      • 2015-04-19
      • 2019-04-14
      • 2013-10-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多