问题
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