国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > JavaScript > 正文

輕松創建nodejs服務器(6):作出響應

2019-11-20 13:40:33
字體:
來源:轉載
供稿:網友

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

我們來看看如何實現它:

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

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

復制代碼 代碼如下:

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;

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

復制代碼 代碼如下:

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;

正如上述代碼所示,當請求無法路由的時候,我們也返回了一些相關的錯誤信息。
最后,我們需要對我們的server.js進行重構以使得它能夠將請求處理程序通過請求路由返回的內容響應給瀏覽器,如下所示:

復制代碼 代碼如下:

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;

如果我們運行重構后的應用:

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

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

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 合作市| 云浮市| 桂林市| 开封县| 扎兰屯市| 赣州市| 衡水市| 托克逊县| 北海市| 石景山区| 郯城县| 彭泽县| 长岛县| 乐陵市| 泽州县| 白山市| 无为县| 沙河市| 叶城县| 阆中市| 来凤县| 莱芜市| 天等县| 深泽县| 金川县| 辽源市| 满城县| 贡觉县| 永济市| 四平市| 和林格尔县| 长武县| 同心县| 大姚县| 千阳县| 枝江市| 伊吾县| 徐水县| 乐亭县| 翼城县| 米林县|