モジュールを使用して、2秒ごとにHTTPリクエストを作成しようとしていnode-cron
ます。
私は apiCalls.js を持っています。
var http = require('https');
module.exports = {
getData: function(callback) {
var options = {
host: 'google.com',
path: '/index.html'
};
var req = http.get(options, function(res) {
console.log('STATUS: ' + res.statusCode);
console.log('HEADERS: ' + JSON.stringify(res.headers));
var bodyChunks = [];
res.on('data', function(chunk) {
bodyChunks.push(chunk);
}).on('end', function() {
var body = Buffer.concat(bodyChunks);
console.log('BODY: ' + body);
callback(body);
})
});
req.on('error', function(e) {
console.log('ERROR: ' + e.message);
});
}
}
これはうまくいきます。これを 2 秒ごとに呼び出し、後でビュー ファイルを更新したいと思います。socket.io
ここでは、react が必要なのか、それともできるのかわかりません。
index.js でこの関数を呼び出しています。
var express = require('express');
var router = express.Router();
var cron = require('node-cron');
var apiCalls = require('../apiCalls')
router.get('/', function(req, res, next) {
var cronJob = cron.schedule('*/2 * * * * *', function(){
apiCalls.getData(function(data){
res.render('index', { title: 'example', data: data });
});
});
cronJob.start();
});
module.exports = router;
しかし、すでにヘッダーを設定しているように見えるため、エラーが発生しています。どうやってやるの?
_http_outgoing.js:503
throw new errors.Error('ERR_HTTP_HEADERS_SENT', 'set');
^
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at validateHeader (_http_outgoing.js:503:11)
ありがとうございました