node.js丢失asynchronous请求中的发布数据
我正在Node.js中做一个简单的表单。 其他一切似乎都在正常工作,但是应该接收发布请求数据的函数永远不会被调用。 以下是相关的代码片段:
if (request.method == 'POST') { var body = ''; console.log(request.body); request.on('data', function (chunk) { console.log("got the post request data"); //nothing logged to console body += chunk; }); request.on('end', onRequestEnd(body, response)); }
onRequestEnd函数确实被调用,但是稍后我的代码会在参数体中只有一个空string时中断。 关键字“数据”是否正确?
代码从这里的答案修改: 如何提取Node.js中的POST数据? 。 如果需要,我会发布更多。
经过很多挫折,我自己解决了这个问题!
我改变了行:
request.on('end', onRequestEnd(body, response));
至:
request.on('end', function() { onRequestEnd(body, response); });
这跟callback有关。 我不确定为什么这个工作,而另一个不通过。 这是我的感受: http : //www.masti-xpress.com/images/Story-of-Every-Programmer.jpg
我将分享我是如何解决这个问题的。 然而,我有另外一个看法,我也会分享一下。 我想要的是在我的“观点”中有这样的东西。
app('/urlToView', function(req, response){ request.on('end', function() { var post = **request.data;** //sanitize data resolver.renderTemplateOr404('start.html', post, request, response); }); }
request.data是在这里要注意的重要事情。 然而,我还没有真正解决如何“不” request.on('end'...)
在我看来, request.on('end'...)
。
关于为什么console.log()会是你如何处理你所做的所有工作的函数的callback。
当我启动服务器时,我在劫持请求之前将其劫持
self.preProcess(self, request, response);
和
preProcess: function onRequest(app, request, response){ processor.preRequest(request); }
最后是我做的preRequest()函数
if (request.method === 'POST') { var postdata = ""; request.on('data', function(postdataChunk){ postdata += postdataChunk; }); request.on('end', function(){ _transformRequest(request, _transformPostdata(postdata)); //this is to set the data on the request }); }
并添加一个console.log(postdataChunk);
这是不是一个问题,因为所有的callback处理得当。
另外,这可能是我愚蠢的问,但你知道console.log(); 不输出到浏览器,但terminal窗口?
这可能不是一个确切的答案,但我希望这会有所帮助。