在Node.js上响应具有非阻塞操作的请求处理程序

时间:2012-02-17 16:02:04

标签: node.js

我正在使用Node Beginner Book学习Node.js。 当我尝试使用非阻塞操作管理请求时,我陷入困境。

如果我转到localhost:8888它返回文件列表,但是如果我转到localhost:8888 / start或/ upload它返回404 not found。为什么呢?

index.js

var server = require("./server");
var router = require("./router");
var requestHandlers = require("./requestHandlers");
var handle = {};
handle["/"] = requestHandlers.start;
handle["start"] = requestHandlers.start;
handle["upload"] = requestHandlers.upload;
server.start(router.route,handle);

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.");

   route(handle, pathname, response);
  }

  http.createServer(onRequest).listen(8888);
  console.log("Server has started.");
}

exports.start = start;

requestHandlers.js

var exec = require("child_process").exec;

function start(response) {
    console.log("Request handler 'start' was called.");
    exec("ls -lah", function (error, stdout, stderr) {
        response.writeHead(200, {"Content-Type": "text/plain"});
        response.write(stdout);
        response.end();
    });
}

function upload(response) {
    console.log("Request handler 'upload' was called.");
    response.writeHead(200, {"Content-Type": "text/plain"});
    response.write("Hello Upload");
    response.end();
}

exports.start = start;
exports.upload = upload;

router.js

function route(handle, pathname, response) {
   console.log("About to route a request for " + pathname);
   if (typeof handle[pathname] === 'function') {
       handle[pathname](response);
   } else {
      console.log("No request handler found for " + pathname);
      response.writeHead(404, {"Content-Type": "text/plain"});
      response.write("404 Not found");
     response.end();
   }
 }

 exports.route = route;

3 个答案:

答案 0 :(得分:2)

它是index.js中的处理程序键,它们应该是:

handle["/"] = requestHandlers.start;
handle["/start"] = requestHandlers.start;
handle["/upload"] = requestHandlers.upload;

我已经测试了这个,这肯定是问题

答案 1 :(得分:0)

处理程序键不应该以“/”开头吗?

答案 2 :(得分:0)

response作为参数添加到exec调用中,如下所示:

function start(response) {
    console.log("Request handler 'start' was called.");
    exec("ls -lah", response, function (error, stdout, stderr) {
        //          ^^^^^^^^
        response.writeHead(200, {"Content-Type": "text/plain"});
        response.write(stdout);
        response.end();
    });
}