我正在阅读http://www.nodebeginner.org中的教程,并且在数据输出中有一个奇怪的行为。我知道,在Stackoverflow上也有类似的问题,但没有答案。因此,我有以下Web服务器代码:
//server.js
var http = require('http')
var url = require('url')
函数start(route,handle){
函数onRequest(请求,响应){
var postData =“”
var pathname = url.parse(request.url).pathname
console.log(“请求” +路径名+“已收到。”)
request.setEncoding('utf8')
request.addListener(“data”,function(postDataChunk){
postData + = postDataChunk
console.log(“收到的POST数据块'” + postDataChunk +“'。”)
})
request.addListener(“end”,function(){
路线(句柄,路径名,响应,postData)
})
var content = route(句柄,路径名,响应)
}
http.createServer(onRequest).listen(80,'192.168.1.34')
console.log(“服务器已启动”)
}
exports.start =开始
调用requestHandler.upload的router.js代码-我的 buggy 功能
//router.js
函数route(句柄,路径名,响应,postData){
console.log(“关于路由请求” +路径名)
if(typeof handle [pathname] ==='function'){
handle [pathname](response,postData)//调用requestHandler.upload
} 别的 {
console.log(“找不到“+路径名的请求处理程序”)
response.writeHead(404,{'Content-Type':'text/plain'})
response.write(“404未找到”)
response.end()
}
}
和requestHandler.upload的代码
//requestHandler.js
函数upload(response,postData){
console.log(“请求处理程序'upload'用POST数据调用:” + postData);//工作正常
response.writeHead(200,{“Content-Type”:“text/plain”});
response.write(“您已发送:” + postData);//丑陋
response.end();
}
假设在POST数据中有一个字符串text=123
。此函数的第一行输出实际数据,例如"Request handler 'upload' was called with POST data: text=123"
。虽然,此行response.write("You've sent: " + postData);
在浏览器的下一条消息中输出:You've sent: undefined
。
我究竟做错了什么?
最佳答案
在server.js
的代码行中:
var content = route(handle, pathname, response)
首先在
"end"
事件监听器中调用之前运行,执行该函数但省略postData
参数。运行...response.write("You've sent: " + postData);
response.end();
因此,发送回浏览器的响应是:
You've sent: undefined
此后将触发
"end"
事件,并且事件监听器会调用...route(handle, pathname, response, postData)
可以正确传递
postData
并将其正确输出到控制台。对response.write(...)
的调用不会第二次发回到浏览器中,因为此时响应已结束。我希望这可以解释问题。
编辑答案是删除调用
var content = route(handle, pathname, response)
当客户端完成发布数据并且此时您已正确运行
"end"
函数时,将调用route
事件。关于node.js - node.js中的奇怪行为,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12326039/