http://www.nodebeginner.orgでチュートリアルを読んでいますが、データ出力に奇妙な動作があります。Stackoverflow にも同様の質問がありますが、答えはありません。だから私はこのウェブサーバーのコードを持っています:
//server.js
var http = require('http')
var url = require('url')
関数の開始 (ルート、ハンドル) {
関数 onRequest(リクエスト、レスポンス) {
var postData = ""
var パス名 = url.parse(request.url).pathname
console.log("" + パス名 + " のリクエストを受け取りました。")
request.setEncoding('utf8')
request.addListener("データ", function(postDataChunk) {
postData += postDataChunk
console.log("受信した POST データ チャンク '" + postDataChunk +"'.")
}))
request.addListener("終了", function() {
ルート (ハンドル、パス名、応答、postData)
}))
var content = route(ハンドル、パス名、レスポンス)
}
http.createServer(onRequest).listen(80, '192.168.1.34')
console.log("サーバーが起動しました")
}
exports.start = 開始
requestHandler.upload を呼び出す router.js のコード - 私のバグのある関数
//router.js
関数ルート(ハンドル、パス名、応答、postData){
console.log("" + パス名のリクエストをルーティングしようとしています)
if (ハンドルの種類[パス名] === '関数') {
handle[pathname](response, postData) //requestHandler.upload を呼び出します
} そうしないと {
console.log("No request handler found for " + pathname)
response.writeHead(404, {'Content-Type': 'text/plain'})
response.write("404 見つかりません")
応答.終了()
}
}
そして requestHandler.upload のコード
//requestHandler.js
関数アップロード(応答、postData){
console.log("リクエスト ハンドラ 'upload' が POST データで呼び出されました: " + postData); //正常に動作します
response.writeHead(200, {"Content-Type": "text/plain"});
response.write("送信しました: " + postData); //醜い動作
応答.終了();
}
POST データに string があると仮定しましょうtext=123。この関数の最初の行は、 のような実数データを出力します"Request handler 'upload' was called with POST data: text=123"。ただし、この行response.write("You've sent: " + postData);はブラウザの次のメッセージに出力します: You've sent: undefined. 私は何を間違っていますか?