响应请求
在之前的代码中,我们对浏览器的请求做出了响应,使用response.write("Hello World");
简单地来说,响应请求有以下几种方式:
使用 return 关键字
这是一种不好的实现方式,示例:
- 修改requestHandlers.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;
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;
var http = require("http");
var url = require("url");//引用url模块
function start(route, handle) {
function onRequest(request, response) {
//将请求中的url字符串转换成url对象之后获取pathname赋值给变量
var pathname = url.parse(request.url).pathname;
console.log("Request for " + pathname + " received.");
//将获取到的pathname交给route处理
var content = route(handle, pathname);//将返回值赋值于一个变量
response.writeHead(200, {"Content-Type": "text/plain"});
response.write(content);//将变量响应到前端
response.end();
}
http.createServer(onRequest).listen(8888);
console.log("Server has started.");
}
exports.start = start;
以上代码重构之后,一切工作都是挺正常的。但是,由于node.js是可以在不增加额外线程的情况下,依然可以对任务进行并行处理。——也就是说node.js是单线程的。
如果在以上代码中加入等待操作,就会看出差别。
function start() {
console.log("Request handler 'start' was called.");
function sleep(milliSeconds){
var startTime = new Date().getTime();
while(new Date().getTime() < startTime + milliSeconds);
}
sleep(10000);
return "Hello start";//增加返回值
}
function upload() {
console.log("Request handler 'upload' was called.");
return "Hello upload";////增加返回值
}
exports.start = start;
exports.upload = upload;
- 此时,如果在浏览器键入 http://localhost:8888/ 和 http://localhost:8888/upload
- 在第一个标签按下回车之后,立即按下第二个标签回车,可以发现两个标签都等待了十秒。正常应该是第一个等待十秒,第二个则是立即返回。