欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

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

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

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

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

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

我們需要將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;

同樣的,請(qǐng)求路由需要將請(qǐng)求處理程序返回給它的信息返回給服務(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)請(qǐng)求無(wú)法路由的時(shí)候,我們也返回了一些相關(guān)的錯(cuò)誤信息。
最后,我們需要對(duì)我們的server.js進(jìn)行重構(gòu)以使得它能夠?qū)⒄?qǐng)求處理程序通過(guò)請(qǐng)求路由返回的內(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)用:

請(qǐng)求http://localhost:8888/start,瀏覽器會(huì)輸出“Hello Start”,
請(qǐng)求http://localhost:8888/upload會(huì)輸出“Hello Upload”,
而請(qǐng)求http://localhost:8888/foo 會(huì)輸出“404 Not found”。

這感覺(jué)不錯(cuò),下一節(jié)我們要來(lái)了解一個(gè)概念:阻塞操作。

相關(guān)文章

最新評(píng)論