Create reusable http request Node.js function

隐身守侯 提交于 2021-02-08 06:51:35

问题


I'm trying to creating a script to trigger an IFTTT notification. What I got working so far is:

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)

But what I would like is to do, is to create a reusable function so I can call it with different parameters in different situations.

What I came up with so far:

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);

But nothing happens and I don't get any errors when I run: "node script.js" in the terminal

Can someone help me with this?

Thanks!


回答1:


Your function is making a request but is not sending it.

Try with this:

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();
}


来源:https://stackoverflow.com/questions/38730465/create-reusable-http-request-node-js-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!