DIV CSS 佈局教程網

打造 Node.js 伺服器(10):完整處理 POST 請求
編輯:關於JavaScript     

到目前為止,我們做的伺服器還沒有實際用途。接下來要動真格的:讓使用者在頁面上輸入文字,透過 POST 送到伺服器,伺服器再把內容回顯出來。

步驟一:做一個輸入表單

首先在 start 處理函式中輸出一個包含 textarea 的表單頁面。requestHandlers.js 修改如下:

function start(response) {
  console.log("Request handler 'start' was called.");
  var body = '<html>' +
    '<head>' +
    '<meta http-equiv="Content-Type" content="text/html; ' +
    'charset=UTF-8" />' +
    '</head>' +
    '<body>' +
    '<form action="/upload" method="post">' +
    '<textarea name="text" rows="20" cols="60"></textarea>' +
    '<input type="submit" value="Submit text" />' +
    '</form>' +
    '</body>' +
    '</html>';
  response.writeHead(200, {"Content-Type": "text/html"});
  response.write(body);
  response.end();
}

function upload(response) {
  console.log("Request handler 'upload' was called.");
  response.writeHead(200, {"Content-Type": "text/plain"});
  response.write("Hello Upload");
  response.end();
}

exports.start = start;
exports.upload = upload;

在瀏覽器中訪問 https://localhost:8888/start 就能看到效果了。

步驟二:在伺服器端收集 POST 資料

接下來要讓使用者提交表單時,觸發 /upload 處理函式去處理 POST 請求。

為了使整個過程保持非阻塞,Node.js 會把 POST 資料拆分成許多小資料塊,然後透過觸發特定事件,把這些小塊陸續交給回呼函式。這裡有兩個關鍵事件:data 事件(代表新的資料塊到了)以及 end 事件(代表所有資料都接收完畢)。

我們透過在 request 物件上註冊監聽器來實作。這個 request 物件,就是每次收到 HTTP 請求時被傳給 onRequest 回呼的那個。

把程式碼放進伺服器裡,server.js 修改如下:

var http = require("http");
var url = require("url");

function start(route, handle) {
  function onRequest(request, response) {
    var postData = "";
    var pathname = url.parse(request.url).pathname;
    console.log("Request for " + pathname + " received.");

    request.setEncoding("utf8");

    request.addListener("data", function(postDataChunk) {
      postData += postDataChunk;
      console.log("Received POST data chunk '" + postDataChunk + "'.");
    });

    request.addListener("end", function() {
      route(handle, pathname, response, postData);
    });
  }
  http.createServer(onRequest).listen(8888);
  console.log("Server has started.");
}

exports.start = start;

這段程式碼做了三件事:先設定接收資料的編碼為 UTF-8;接著註冊 data 事件的監聽器,把每次收到的新資料塊累加到 postData 變數;最後把請求路由的呼叫移到 end 事件處理函式中,以確保它只在所有資料都收完之後才觸發,而且只觸發一次。我們同時把 POST 資料傳給請求路由,因為後續的處理函式會用到。

這裡有個細節值得強調:路由呼叫必須放在 end 而非 data 裡。如果放在 data 事件中,每收到一個資料塊就會觸發一次路由,導致同一個請求被重複處理好幾次。

步驟三:把資料沿路由傳到處理函式

改一下 router.js:

function route(handle, pathname, response, postData) {
  console.log("About to route a request for " + pathname);
  if (typeof handle[pathname] === 'function') {
    handle[pathname](response, postData);
  } else {
    console.log("No request handler found for " + pathname);
    response.writeHead(404, {"Content-Type": "text/plain"});
    response.write("404 Not found");
    response.end();
  }
}

exports.route = route;

然後在 requestHandlers.js 中,把資料呈現在 upload 的回應裡:

function start(response, postData) {
  console.log("Request handler 'start' was called.");
  var body = '<html>' +
    '<head>' +
    '<meta http-equiv="Content-Type" content="text/html; ' +
    'charset=UTF-8" />' +
    '</head>' +
    '<body>' +
    '<form action="/upload" method="post">' +
    '<textarea name="text" rows="20" cols="60"></textarea>' +
    '<input type="submit" value="Submit text" />' +
    '</form>' +
    '</body>' +
    '</html>';
  response.writeHead(200, {"Content-Type": "text/html"});
  response.write(body);
  response.end();
}

function upload(response, postData) {
  console.log("Request handler 'upload' was called.");
  response.writeHead(200, {"Content-Type": "text/plain"});
  response.write("You've sent: " + postData);
  response.end();
}

exports.start = start;
exports.upload = upload;

步驟四:只取出我們感興趣的部分

最後還有一件事要處理。目前我們是把整個請求訊息體都傳給了請求路由與處理函式,但我們真正感興趣的其實只有 text 這個欄位。

這可以用前面介紹過的 querystring 模組來實現:

var querystring = require("querystring");

function start(response, postData) {
  console.log("Request handler 'start' was called.");
  var body = '<html>' +
    '<head>' +
    '<meta http-equiv="Content-Type" content="text/html; ' +
    'charset=UTF-8" />' +
    '</head>' +
    '<body>' +
    '<form action="/upload" method="post">' +
    '<textarea name="text" rows="20" cols="60"></textarea>' +
    '<input type="submit" value="Submit text" />' +
    '</form>' +
    '</body>' +
    '</html>';
  response.writeHead(200, {"Content-Type": "text/html"});
  response.write(body);
  response.end();
}

function upload(response, postData) {
  console.log("Request handler 'upload' was called.");
  response.writeHead(200, {"Content-Type": "text/plain"});
  response.write("You've sent the text: " + querystring.parse(postData).text);
  response.end();
}

exports.start = start;
exports.upload = upload;

querystring.parse() 會把 text=xxx 這樣的字串轉成物件,接著就能用 .text 精準取出欄位值。

以上就是處理 POST 資料的完整流程。對照整個系列,可以發現 Node 的請求處理始終圍繞著同一個核心觀念:一切都是事件,結果都在回呼裡。下一節我們將實現圖片上傳的功能,那時會需要處理 multipart 格式,比現在的 query string 更複雜一些。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved