【问题标题】:Strange behavior in node.jsnode.js 中的奇怪行为
【发布时间】:2012-09-01 19:20:07
【问题描述】:

我正在阅读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 数据中有一个字符串text=123。这个函数的第一行输出像"Request handler 'upload' was called with POST data: text=123"这样的真实数据。虽然,这一行 response.write("You've sent: " + postData); 在浏览器中输出下一条消息:You've sent: undefined。 我做错了什么?

【问题讨论】:

    标签: node.js


    【解决方案1】:

    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(...) 的调用不会第二次回传到浏览器,因为此时的响应已经结束。

    我希望这能解释问题。

    EDIT答案是去掉调用

    var content = route(handle, pathname, response)
    

    当客户端完成发布数据并且此时您正在正确运行route 函数时,将调用"end" 事件。

    【讨论】:

    • 非常感谢,这是我自己犯的严重错误。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-04-16
    • 1970-01-01
    • 1970-01-01
    • 2017-06-13
    • 1970-01-01
    • 2017-12-12
    • 1970-01-01
    相关资源
    最近更新 更多