2016-10-24 4 views
5

こんにちは私はダッシュボードにOneSignal APIを実装しようとしていましたが、エクスプレスサーバー内でAPI外部呼び出しを行うことが可能かどうか疑問です。ここでエクスプレスサーバ内で外部APIコールを作成するにはどうすればよいですか?

は一例です。

var sendNotification = function(data) { 
    var headers = { 
    "Content-Type": "application/json; charset=utf-8", 
    "Authorization": "Basic NGEwMGZmMjItY2NkNy0xMWUzLTk5ZDUtMDAwYzI5NDBlNjJj" 
    }; 

    var options = { 
    host: "onesignal.com", 
    port: 443, 
    path: "/api/v1/notifications", 
    method: "POST", 
    headers: headers 
    }; 

    var https = require('https'); 
    var req = https.request(options, function(res) { 
    res.on('data', function(data) { 
     console.log("Response:"); 
     console.log(JSON.parse(data)); 
    }); 
    }); 

    req.on('error', function(e) { 
    console.log("ERROR:"); 
    console.log(e); 
    }); 

    req.write(JSON.stringify(data)); 
    req.end(); 
}; 

ここでは、

app.post('/path', function(req, res){ 


var message = { 
    app_id: "5eb5a37e-b458-11e3-ac11-000c2940e62c", 
    contents: {"en": "English Message"}, 
    included_segments: ["All"] 
}; 

sendNotification(message); 
}); 

ありがとうアプリルートです!

答えて

7

サーバ内でAPI外部呼び出しを行うことが可能かどうか疑問です。あなたが表示またはrequest moduleのようなものの上に構築された高いレベルのモジュールの1されているよう

確かに、あなたはhttp.request()とのNode.jsアプリから任意の外部サーバに接続することができます。

const request = require('request'); 
request('http://www.google.com', function (error, response, body) { 
    if (!error && response.statusCode == 200) { 
    console.log(body) // Show the HTML for the Google homepage. 
    } 
}); 

か、約束を使用して::ここで

は、要求モジュールのホーム・ページから、簡単な例です

const rp = require('request-promise'); 
rp('http://www.google.com').then(body => { 
    console.log(body); 
}).catch(err => { 
    console.log(err); 
}); 
関連する問題