亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

輕松創(chuàng)建nodejs服務(wù)器(6):作出響應(yīng)

 更新時間:2014年12月18日 10:11:57   投稿:junjie  
這篇文章主要介紹了輕松創(chuàng)建nodejs服務(wù)器(6):作出響應(yīng),我們接著改造服務(wù)器,讓請求處理程序能夠返回一些有意義的信息,需要的朋友可以參考下

我們接著改造服務(wù)器,讓請求處理程序能夠返回一些有意義的信息。

我們來看看如何實(shí)現(xiàn)它:

1、讓請求處理程序通過onRequest函數(shù)直接返回(return())他們要展示給用戶的信息。
2、讓我們從讓請求處理程序返回需要在瀏覽器中顯示的信息開始。

我們需要將requestHandler.js修改為如下形式:

復(fù)制代碼 代碼如下:

function start() {
  console.log("Request handler 'start' was called.");
  return "Hello Start";
}
function upload() {
  console.log("Request handler 'upload' was called.");
  return "Hello Upload";
}
exports.start = start;
exports.upload = upload;

同樣的,請求路由需要將請求處理程序返回給它的信息返回給服務(wù)器。
因此,我們需要將router.js修改為如下形式:

復(fù)制代碼 代碼如下:

function route(handle, pathname) {
  console.log("About to route a request for " + pathname);
  if (typeof handle[pathname] === 'function') {
 return handle[pathname]();
  } else {
 console.log("No request handler found for " + pathname);
 return "404 Not found";
  }
}
 
exports.route=route;

正如上述代碼所示,當(dāng)請求無法路由的時候,我們也返回了一些相關(guān)的錯誤信息。
最后,我們需要對我們的server.js進(jìn)行重構(gòu)以使得它能夠?qū)⒄埱筇幚沓绦蛲ㄟ^請求路由返回的內(nèi)容響應(yīng)給瀏覽器,如下所示:

復(fù)制代碼 代碼如下:

var http = require("http");
var url = require("url");
function start(route, handle) {
  function onRequest(request, response) {
 var pathname = url.parse(request.url).pathname;
 console.log("Request for " + pathname + " received.");
 response.writeHead(200, {"Content-Type": "text/plain"});
 var content = route(handle, pathname);
 response.write(content);
 response.end();
  }
  http.createServer(onRequest).listen(8888);
  console.log("Server has started.");
}
exports.start=start;

如果我們運(yùn)行重構(gòu)后的應(yīng)用:

請求http://localhost:8888/start,瀏覽器會輸出“Hello Start”,
請求http://localhost:8888/upload會輸出“Hello Upload”,
而請求http://localhost:8888/foo 會輸出“404 Not found”。

這感覺不錯,下一節(jié)我們要來了解一個概念:阻塞操作。

相關(guān)文章

最新評論