2016-08-02 42 views
0

我正在尝试创建脚本来触发IFTTT通知。 什么到目前为止,我得到的工作是:创建可重复使用的http请求Node.js功能

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

但没有任何反应,当我跑我没有得到任何错误:“节点的script.js”在终端

谁能帮我和这个?

谢谢!

回答

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

谢谢!这很好用! – svh1985