0

モジュールを使用して、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)

ありがとうございました

4

1 に答える 1

0

問題は、ハンドラーres.render()で 2 秒ごとに何度も何度も呼び出すことにありますroute.get()。リクエスト ハンドラーごとに最終的な res.render() を 1 つしか持つことができません。コーディングした方法では、リクエストが行われた後、2 秒ごとにウェブサイトが自動的に更新されるとは期待できません。クライアントにN秒ごとにリクエストを送信させるか(効率的ではありません)、Webソケットなどのより効率的なものを使用してそれを実現できます。

于 2017-12-26T02:25:39.450 に答える