何时在节点中调用res.on(end)

时间:2013-08-19 13:15:34

标签: javascript node.js coffeescript

我有以下相当简单的代码(在coffeescript中):

http = require 'http'

options =
  hostname: 'somewebsite.com'
  port: 80,
  path: '/'

server = http.createServer  (request, response) ->
  response.writeHead 200, 'text/html'
  req = http.get options, (res) ->
    res.on 'data', (data) -> 
      console.log 'GETTING IT'
      response.write data
    res.on 'end', () ->
      console.log 'GOT IT'
      response.end()

server.listen 80

我的印象是,一旦请求完成,就会调用res.on'end',但每当我执行代码时,都会多次调用回调。有什么帮助吗?

2 个答案:

答案 0 :(得分:0)

所以,我在这里遇到的问题不是res.on('end')被多次调用,而是我正在发出多个请求,因为每个请求都是通过这个循环处理的。因此,当它试图加载图标时,它将再次经历整个过程,当它试图加载任何css文件或文件的html中包含的任何其他内容时,我正在“代理”它将再次通过该过程那部分。

答案 1 :(得分:0)

在这里查看这个例子,我认为这将有助于澄清代码中发生的事情。点击这两个网址localhost:8888和localhost:9999

http = require 'http'
somePortNum = 9999
options =
    hostname: 'localhost'
    port: somePortNum,
    path: '/'

proxyServer = http.createServer  (request, response) ->
  response.writeHead 200, 'text/html'
  response.write 'This server is a proxy server, we will make a request to the server on localhost:9999 and post the response below:\n'
  req = http.get options, (res) ->
    res.on 'data', (data) ->
      response.write data
    res.on 'end', () ->
      response.end()

proxyServer.listen 8888

server2 = http.createServer  (request, response) ->

  response.writeHead 200, 'text/html'
  response.write 'This is a very simple server, it just says hello world'
  response.end()

server2.listen somePortNum