svh1985
svh1985

Reputation: 309

Create reusable http request Node.js function

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!

Upvotes: 1

Views: 990

Answers (1)

Maria Ines Parnisari
Maria Ines Parnisari

Reputation: 17496

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

Upvotes: 2

Related Questions