[英]node.js missing post data in async request
我在Node.js中創建一個簡單的表單。 其他一切似乎都正常工作,但是應該接收post請求數據的函數永遠不會被調用。 這是相關的代碼段:
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會被調用,但是稍后我的代碼會在參數體中只有一個空字符串時中斷。 關鍵字“數據”是否正確?
代碼是從這里的答案修改的: 如何在Node.js中提取POST數據? 。 如果需要,我會發布更多內容。
經過很多挫折我自己解決了這個問題!
我換了一行:
request.on('end', onRequestEnd(body, response));
至:
request.on('end', function() {
onRequestEnd(body, response);
});
它與回調有關。 我不確定為什么會這樣,而另一個則不然。 這就是我的感受: 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'...)
。
關於為什么console.log()將如何處理來自您完成所有這些工作的函數的回調的原因。
當我啟動服務器時,我在我的視圖中劫持了請求
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);
這不是問題,因為所有的回調都得到了妥善處理。
另外,這對我來說可能是非常愚蠢的,但是你知道那個console.log(); 不輸出到瀏覽器,但輸出到終端窗口?
這可能不是你的確切答案,但我希望這有點幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.