2011-09-30 20 views
0

我自学Coffeescript/node,当然,唯一的方法就是使用TDD。这意味着我也在教自己的誓言。我认为,至少有两个问题。一个是 - 获取HTTP响应的异步代码在哪里?另一个是 - 为什么服务器不会给我回应?控制台显示“发送请求”,但不显示“请求已收到”。微小的服务器/客户端设置 - 服务器不响应。提供的所有代码

下面是测试文件:

vows = require 'vows' 
assert = require 'assert' 
EventEmitter = require('events').EventEmitter 

Server = require('./web').WebServer 
Client = require('../lib/client').Client 
Request = require('../lib/request').Request 

PORT = 8080 
SERVER = new Server PORT 
SERVER.start() 
CLIENT = new Client PORT, 'localhost' 
REQUEST = new Request 'GET', '/' 

vows 
    .describe('Sending a request to the server') 
    .addBatch 
    'The request is sent': 
     topic: -> 
     CLIENT.transmit(REQUEST, @callback) 
     return 

     'The response should be what the server sent back': (err, request) -> 
     body = "" 
     request.on 'response', (response) -> 
      response.on 'data', (chunk) -> body += chunk 
     assert.equal body, /Ooga/ 

    .export(module) 

这里是Web服务器对象:

Http = require('http') 

exports.WebServer = class WebServer 

    processRequest = (request, response) -> 
    console.log 'Request received!' 
    console.log request 
    response.writeHead 200, {'Content-Type':'text/plain'} #, 'Content-Length':'6'} 
    response.write 'Ha-ha!' 
    response.end 

    constructor: (@port) -> 
    @server = Http.createServer processRequest 

    start: -> 
    @server.listen @port 

    stop: -> 
    @server.close() 

接下来是客户端代码 - 也很简单。

Http = require 'http' 
Request = require('./request').Request 

exports.Client = class Client 

    constructor: (@port, @host) -> 
    @httpClient = Http.createClient @port, @host 
    @sentence = "I am a Client" 

    transmit: (request, callback = null) -> 
    req = @httpClient.request request.method, request.pathName 
    req.end 
    console.log "Request sent!" 
    if callback 
     callback(null, req) 
    #req.on 'response', (res) -> 
    # callback(null, res) 
     #request.on 'data', (chunk) -> callback(null, chunk) 
    #callback(null, request) 

最后,'请求'对象。

exports.Request = class Request 
    constructor: (@method, @pathName) -> 

    method: -> 
    @method 

    pathName: -> 
    @pathname 

    responseBody: -> 
    @body 

    setResponseBody: (body) -> 
    @body = body 

    appendToResponseBody: (chunk) -> 
    @body += chunk 

这一切都很简单,我真的不知道为什么服务器似乎没有工作。我甚至不担心异步代码应该从服务器获取信息的位置,但我也想弄清楚。

回答

2

啊,你已经犯了一个典型的错误:,你写

req.end 

,你的意思

req.end() 

所以,你的请求没有被实际在所有发送尽管控制台的说法与此相反! (我在你的代码中看到一个response.end。)

顺便说一句,Vows测试代码很漂亮,但它也是一个复杂的框架,带有一些细微的陷阱。你可能想尝试一些简单的东西,比如nodeunit

哦,如果你真的讨厌括号,你可以写do req.end而不是req.end(),但这不是一种常见的风格。

+0

Gah!谢谢。我也是Javascript新手。我正在学习有关誓言疑难问题的非常快,但我真的想要一个可以使用Coffeescript的测试框架。我不认为nodeunit允许..是吗? – Trevoke

+1

它没有很好的记录,但nodeunit实际上已经支持一年CoffeeScript:https://github.com/caolan/nodeunit/pull/6只需运行'nodeunit test.coffee'。 –

+0

整洁。现在,如果我能弄清楚如何让回调工作......但这是另一个问题。马上就来! – Trevoke