2016-08-02 40 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