【问题标题】:Node.js response undefined when connected using http client使用 http 客户端连接时未定义 Node.js 响应
【发布时间】:2012-01-03 12:06:50
【问题描述】:

我是 node.js 的新手,首先创建了一个在端口 5000 上运行的小型 Web 应用程序。当我尝试在本地运行的这个 url(通过浏览器或 curl)时,一切正常,我取回响应。但是,当我在执行“使用誓言的 BDD”时尝试将它与 http 客户端连接时,测试失败了,结果消息是

✗ 

  /GET
    ✗ should respond with 404
    ***TypeError: Cannot read property 'status' of undefined***
    at ClientRequest.<anonymous> (/home/sunil/work/nodal_programs/subscription-engine-processor/sample-test.js:13:23)
    at runTest (/home/sunil/work/nodal_programs/subscription-engine-processor/node_modules/vows/lib/vows.js:132:26)
    at EventEmitter.<anonymous> (/home/sunil/work/nodal_programs/subscription-engine-processor/node_modules/vows/lib/vows.js:85:17)
    at EventEmitter.<anonymous> (events.js:67:17)
    at EventEmitter.emit (/home/sunil/work/nodal_programs/subscription-engine-processor/node_modules/vows/lib/vows.js:236:24)
    at /home/sunil/work/nodal_programs/subscription-engine-processor/node_modules/vows/lib/vows/context.js:31:52
    at ClientRequest.<anonymous> (/home/sunil/work/nodal_programs/subscription-engine-processor/node_modules/vows/lib/vows/context.js:46:29)
    at ClientRequest.<anonymous> (events.js:67:17)
    at ClientRequest.emit (/home/sunil/work/nodal_programs/subscription-engine-processor/node_modules/vows/lib/vows.js:236:24)
    at HTTPParser.onIncoming (http.js:1225:11)
✗ Errored » 1 errored (0.012s)

这里的响应是未定义的。

body = "Not found"; 
response.writeHead(404, {'Content-Type': 'text/plain', 'Content-Length': body.length});     
response.end(body);

这就是我在应用程序中的响应方式。我已经设置了标题内容类型和内容长度。 谁能帮我看看可能是什么问题?

我写的誓言是这样的。

var http = require('http'),
    vows = require('vows'),
    assert = require('assert');

vows.describe("notification").addBatch({
  "/GET": {
    topic: function() {
    http.get({host: 'localhost', port: 1337, path: '/', method: 'GET'}, this.callback) ; 
    },
    'should respond with 404': function(e,res) {
      assert.equal(res.status, 404);
    }
  }
}).run(); 

【问题讨论】:

    标签: node.js vows


    【解决方案1】:

    我对代码进行了更改,并尝试将响应作为回调的第一个参数,将错误作为第二个参数。这对我有用。

    'should respond with 404': function(res,e) {
       assert.equal(res.status, 404);
    }
    

    但是 res 作为唯一参数仍然会引发我上面提到的错误。
    感谢您的支持。

    【讨论】:

      【解决方案2】:

      尝试改变

      'should respond with 404': function(e,res) {
        assert.equal(res.status, 404);
      }
      

      'should respond with 404': function(res) {
        assert.equal(res.status, 404);
      }
      

      根据Node.js HTTP docshttp.request(以及因此http.get)回调不采用err 参数。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-09-24
        • 2014-04-14
        • 2011-06-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多