response.write()不会接受一个string。 它的行为好像没有定义
我已经从response.on('data'...
传递了postData对象,只要我和console.log()
一起工作就可以了。但是,当我尝试postData.toString()
或者将它传递给response.write()
被视为未定义的,我很困惑这种行为。
upload = function(response, postData) { response.writeHead(200, {'Content-Type': 'text/plain'}); console.log(postData); // outputs the data that was posted console.log(typeof postData); // outputs string var item = postData; // successfully sets item equal to postData console.log(item); // outputs the data as expected console.log(typeof item); // outputs string response.write('You\'ve sent: ' + item); //writes "You've sent: undefined" response.end(); }
我的完整代码是: Node.js请求数据事件不发射。 我究竟做错了什么?
我不知道我是否造成问题,或者使用已弃用的方法或什么。 请帮忙。
谢谢。
这个问题似乎在createServer()
callback中 ,它试图两次route()
每个request
和response
– 一次没有postData
,一次使用:
http.createServer(function(request, response) { // ... // routes to `upload()` without a 4th argument // so, `postData` will be `undefined` route(handle, pathname, response); // ... request.on('end', function(postDataChunk) { // ... // routes to `upload()` again, this time with `postData` route(handle, pathname, response, postData); }); }).listen(portToUse);
由于每次调用route()
,反过来upload()
都试图write()
和end()
response
,所以只有第一个实际上能write()
任何东西。
这是因为在调用response.end()
之后response.end()
不能做任何事情,并在response.end()
后closuresnet.Socket
。
但是, console.log()
没有这个依赖关系,所以你应该看到两个调用的日志:
undefined // from: console.log(postData) 'undefined' // from: console.log(typeof postData) undefined // from: console.log(item) 'undefined' // from: console.log(typeof item) foo=bar&baz=qux // from: console.log(postData) 'string' // from: console.log(typeof postData) foo=bar&baz=qux // from: console.log(item) 'string' // from: console.log(typeof item)