![](/img/trans.png)
[英]Undefined value in the response when sending JSON object to the client- Node.js
[英]Node.js response undefined when connected using http client
我是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);
这就是我在应用程序中的响应方式。 我已经设置了标题content-type和content-length。 请问有人可能会帮助我吗?
我写的誓言是这个。
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();
我对代码进行了更改,并尝试将响应作为回调的第一个参数,将错误作为第二个参数。 这对我有用。
'should respond with 404': function(res,e) {
assert.equal(res.status, 404);
}
但是res作为唯一的参数仍然会引发错误,如上所述。
谢谢你的支持。
尝试改变
'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文档 , http.request
(以及因此的http.get
)回调不带有err
参数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.