尝试编写以下代码: index.js
const http = require('http');
const port = 9090;
const url = require('url');
const handlers = require('./handlers.js');
http.createServer((req, res) => {
req.path = url.parse(req.url).pathname;
let handler = handlers(req.path);
handler(req, res);
}).listen(port);
handlers.js:
const fs = require('fs');
const homeHandler = require('./handlers/home-handler');
const contentHandler = require('./handlers/content-handler');
module.exports = (path) => {
switch (path) {
case '/':
return homeHandler;
case '/content':
return contentHandler;
}
}
home-handler.js
const fs = require('fs')
module.exports = (req, res) => {
fs.readFile('./index.html', (err, data) => {
if (err) {
console.log(err.message);
return;
}
res.writeHead(200, {
'content-type': 'text/html'
});
res.write(data);
res.end();
return;
});
};
当我“启动程序”并在浏览器localhost:9090
中运行时,函数处理程序在浏览器中执行,但在调试控制台中抛出:
TypeError: handler is not a function
使用console.log(handler)
显示handler
是函数,同时instanceof
显示handler
是函数的实例。这是什么问题?
最佳答案
您的处理程序
函数仅处理两个特定输入:/
和/content
。任何其他请求都会产生错误,因为处理程序
不会返回函数。
您可能会说,“那很好!我不请求这组两条路径之外的路径,”但我认为您可能是错的。
大多数浏览器除了请求您输入的实际 URL 之外,还会通过请求 /favicon.ico
来请求网站图标。如果浏览器这样做对于此附加网站图标请求,您将看到预期请求的成功结果(正如您所做的那样),但也会看到附加网站图标请求的失败消息,您尚未设置代码来处理该请求。
我建议添加一个默认的调试处理程序:
module.exports = (path) => {
switch (path) {
case '/':
return homeHandler;
case '/content':
return contentHandler;
default:
(req, res) => {
res.end("Path not handled");
console.warn("No handler for", req.url);
}
}
}
关于javascript - 函数已执行,但抛出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48407923/