我正在阅读http://www.nodebeginner.org中的教程,我在数据输出中有一个奇怪的行为。我知道,Stackoverflow 上有一个类似的问题,但没有答案。所以我有这个网络服务器代码:
//server.js
var http = 要求('http')
var url = 需要('url')
功能开始(路线,句柄){
函数 onRequest(请求,响应){
var postData = ""
var pathname = url.parse(request.url).pathname
console.log("请求 " + 路径名 + " 已收到。")
request.setEncoding('utf8')
request.addListener("数据", 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("服务器已启动")
}
出口.开始 = 开始
调用 requestHandler.upload 的 router.js 代码 - 我的错误函数
//路由器.js
功能路线(句柄,路径名,响应,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 未找到")
响应.end()
}
}
以及 requestHandler.upload 的代码
//requestHandler.js
函数上传(响应,postData){
console.log("请求处理程序 'upload' 是用 POST 数据调用的:" + postData); //工作正常
response.writeHead(200, {"Content-Type": "text/plain"});
response.write("你已经发送:" + postData); //丑陋的工作
response.end();
}
假设在 POST 数据中有一个 string text=123。此函数的第一行输出真实数据,例如"Request handler 'upload' was called with POST data: text=123". 虽然,这一行在response.write("You've sent: " + postData);浏览器中输出下一条消息:You've sent: undefined. 我究竟做错了什么?