3

我正在阅读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. 我究竟做错了什么?

4

1 回答 1

3

在您的代码中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

于 2012-09-07T22:34:41.643 回答