輕鬆建立nodejs伺服器(10):處理POST請求,nodejspost

來源:互聯網
上載者:User

輕鬆建立nodejs伺服器(10):處理POST請求,nodejspost

目前為止,我們做的伺服器沒有實際的用處,接下來我們開始實現一些實際有用的功能。

我們要做的是:使用者選擇一個檔案,上傳該檔案,然後在瀏覽器中看到上傳的檔案。

首先我們需要一個文本區(textarea)供使用者輸入內容,然後通過POST請求提交給伺服器。

我們在start事件處理器裡添加代碼,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;

通過在瀏覽器中訪問http://localhost:8888/start就可以看到效果了。

接下來我們要實現當使用者提交表單時,觸發/upload請求處理常式處理POST請求。

為了使整個過程非阻塞,Node.js會將POST資料拆分成很多小的資料區塊,然後通過觸發特定的事件,將這些小資料區塊傳遞給回呼函數。這裡的特定的事件有data事件(表示新的小資料區塊到達了)以及end事件(表示所有的資料都已經接收完畢)。

我們通過在request對象上註冊監聽器(listener) 來實現。這裡的 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資料傳遞給請求路由,因為這些資料,請求處理常式會用到。

接下來在/upload頁面,展示使用者輸入的內

我們來改一下 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;

我們最後要做的是: 當前我們是把請求的整個訊息體傳遞給了請求路由和請求處理常式。我們應該只把POST資料中,我們感興趣的部分傳遞給請求路由和請求處理常式。在我們這個例子中,我們感興趣的其實只是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;

好了,以上就是關於處理POST資料的全部內容。

下一節,我們將實現圖片上傳的功能。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.