TypeError: Cannot call method 'writeHead' of undefined
发布于 3年前 作者 mathewxiang 2532 次浏览

http://www.nodebeginner.org/index-zh-cn.html

照着这个在学习,可是进行到了不到一半的时候遇到标题中提到的问题.这个是为什么呢?


(1)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);

(2)调用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;

(3)调用router.js

function route(handle, pathname, response) {
    console.log("About to route a request for " + pathname);
    if (typeof handle[pathname] === 'function') {
        handle[pathname]();

    }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;

(4)route调用requestHandlers.js

var exec = require("child_process").exec;
function start(response) {
  console.log("Request handler 'start' was called.");
  exec("find /", { timeout: 10000, maxBuffer: 20000*1024 },
    function (error, stdout, stderr) {
      response.writeHead(200, {"Content-Type": "text/plain"});
      //response.setHeader("Content-Type", "text/html");
      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;
6 回复

start 函数谁调用的呢? 看起来像是http请求的一个handler~,但是上面代码中没有建立http服务。

信息不够,只能确定你传入 start函数的对象,不是一个 httpResponse对象

十分抱歉,各位,找到问题了. 在上面的代码中第三段

(3)调用router.js

 if (typeof handle[pathname] === 'function') {
        handle[pathname]();

上面的函数没有把response参数传递过去.

感谢fish的回答.

handlepathname; 谁因为这句话? 我也遇到了问题 还是没有解决!

@GuoliangChen 同问,我甚至直接复制源码了,还是出现错误。

handle[pathname](response);

还是出现上面的错误。

@GuoliangChen route.js 中 route 方法的参数和 server.js 中的不一致。改成一致的就好了。

回到顶部