创建可重用的http请求Node.js函数 [英] Create reusable http request Node.js function

查看:59
本文介绍了创建可重用的http请求Node.js函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个脚本来触发IFTTT通知.到目前为止,我的工作是:

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

但是什么也没发生,我在终端上运行"node script.js"也没有任何错误

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

有人可以帮我吗?

谢谢!

推荐答案

您的函数正在发出请求,但未发送请求.

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

尝试一下:

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

这篇关于创建可重用的http请求Node.js函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆