nodejs获得服务器响应,轻松创建nodejs服务器(6):作出响应
我們接著改造服務(wù)器,讓請求處理程序能夠返回一些有意義的信息。
我們來看看如何實(shí)現(xiàn)它:
1、讓請求處理程序通過onRequest函數(shù)直接返回(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;
同樣的,請求路由需要將請求處理程序返回給它的信息返回給服務(wù)器。
因此,我們需要將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;
正如上述代碼所示,當(dāng)請求無法路由的時(shí)候,我們也返回了一些相關(guān)的錯(cuò)誤信息。
最后,我們需要對我們的server.js進(jìn)行重構(gòu)以使得它能夠?qū)⒄埱筇幚沓绦蛲ㄟ^請求路由返回的內(nèi)容響應(yīng)給瀏覽器,如下所示:
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”。
這感覺不錯(cuò),下一節(jié)我們要來了解一個(gè)概念:阻塞操作。
總結(jié)
以上是生活随笔為你收集整理的nodejs获得服务器响应,轻松创建nodejs服务器(6):作出响应的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: SharePoint:扩展DVWP -
- 下一篇: Asp.net高级程序设计之服务器控件(