节点js response.end

时间:2016-04-13 06:14:11

标签: node.js

我有点问题......

 var server = http.createServer(function (req, res, data) {
    var url = 'http://localhost:11918/api/log';

    http.get(url, function (res) {
        var body = '';
        res.on('data', function (chunk) {
            body += chunk;
        });
        res.on('end', function () {
            var data = JSON.parse(body);           
            Data.emit('JsData', data);
        });
    }).on('error', function (e) {
        console.log("Got an error: ", e);
    });    

    Data.on('JsData', function (message) {
        res.writeHead(200, { "Content-Type": "text/plain" });
        res.write(JSON.stringify(message));
        res.end();
    });
});

错误:写完后

它很好但是可以在服务器上重写几次....? 怎么样?

1 个答案:

答案 0 :(得分:0)

我用它......它有效:

var http = require('http');
var url = require('url');
var querystring = require('querystring');
var request = require('request');
var EventEmitter = require("events").EventEmitter;
var Data = new EventEmitter();


var server = http.createServer(function (req, res) {

    var url = 'http://localhost:11918/api/log';   
    http.get(url, function (res) {
        var body = '';
        res.on('data', function (chunk) {
            body += chunk;
        });
        res.on('end', function () {
            var data = JSON.parse(body);           
            Data.emit('JsData', data);
        });
    }).on('error', function (e) {
        console.log("Got an error: ", e);
    });    
        Data.on('JsData', function (message) {                              
        res.writeHead(200, { "Content-Type": "application/json" });     
        res.end(JSON.stringify(message));
    });

});

但我不知道这是否是最好的方法