Node.js报错:“router[pathName] is not a function”
1. module文件夹中的 route1.js
module.exports = {
error: function(req,res) {
res.write('错误页面')
},
login: function(req,res) {
res.write('登录')
},
registor: function(req,res) {
res.write('注册')
}
}
2.route.js
var http=require('http')
var url=require('url')
var router=require('./module/route1')
http.createServer(function(req,res){
res.writeHead(200,{'content-Type':'text/html;charset=utf-8'})
if(req.url!=='/favicon.ico'){
var pathName=url.parse(req.url).pathname.replace(/\//,'')
console.log(pathName)
router[pathName](req,res)
}res.end()
}).listen(8000)
console.log('服务器在http://localhost:8000上运行')
3.打开vscode中的终端
 4.输入node命令操作
 5.发现route报错

D:\vscode\项目\test\route.js:10
router[pathName](req,res)
TypeError: router[pathName] is not a function
at Server.<anonymous> (D:\vscode\项目\test\route.js:10:25)
at Server.emit (events.js:127:13)
at parserOnIncoming (_http_server.js:642:12)
at HTTPParser.parserOnHeadersComplete (_http_common.js:117:17)
解决方法
分析route报错原因,查找错误点,理解"router[pathName] is not a function",围绕报错原因中的router[pathName]找解决方法。
解决方法: 给router[pathName]添加一个try块与catch块,try语句允许我们定义在执行时进行错误测试的代码块。catch 语句允许我们定义当 try 代码块发生错误时,所执行的代码块。catch语句中的router[‘error’]的error为代码块发生错误后跳转到的页面,即为错误页面。
try {
router[pathName](req,res)
}catch (error){
router['error'](req,res)
}
解决报错后,测试代码
1.在http:localhost:8000/后面添加login,跳转为登录页面
 2.在http:localhost:8000/后面添加registor,跳转为注册页面
 3.若代码发生错误,跳转为错误页面 
|