轻松创建nodejs服务器(6):作出响应
我们接着改造服务器,让请求处理程序能够返回一些有意义的信息。
我们来看看如何实现它:
1、让请求处理程序通过onRequest函数直接返回(return())他们要展示给用户的信息。
2、让我们从让请求处理程序返回需要在浏览器中显示的信息开始。
我们需要将requestHandler.js修改为如下形式:
functionstart(){
console.log("Requesthandler'start'wascalled.");
return"HelloStart";
}
functionupload(){
console.log("Requesthandler'upload'wascalled.");
return"HelloUpload";
}
exports.start=start;
exports.upload=upload;
同样的,请求路由需要将请求处理程序返回给它的信息返回给服务器。
因此,我们需要将router.js修改为如下形式:
functionroute(handle,pathname){
console.log("Abouttoroutearequestfor"+pathname);
if(typeofhandle[pathname]==='function'){
returnhandle[pathname]();
}else{
console.log("Norequesthandlerfoundfor"+pathname);
return"404Notfound";
}
}
exports.route=route;
正如上述代码所示,当请求无法路由的时候,我们也返回了一些相关的错误信息。
最后,我们需要对我们的server.js进行重构以使得它能够将请求处理程序通过请求路由返回的内容响应给浏览器,如下所示:
varhttp=require("http");
varurl=require("url");
functionstart(route,handle){
functiononRequest(request,response){
varpathname=url.parse(request.url).pathname;
console.log("Requestfor"+pathname+"received.");
response.writeHead(200,{"Content-Type":"text/plain"});
varcontent=route(handle,pathname);
response.write(content);
response.end();
}
http.createServer(onRequest).listen(8888);
console.log("Serverhasstarted.");
}
exports.start=start;
如果我们运行重构后的应用:
请求http://localhost:8888/start,浏览器会输出“HelloStart”,
请求http://localhost:8888/upload会输出“HelloUpload”,
而请求http://localhost:8888/foo会输出“404Notfound”。
这感觉不错,下一节我们要来了解一个概念:阻塞操作。