NodeJs——router报错原因

 

rout.js

var http  =  require('http');
var url = require('url');
var router = require('./models/router.js');

http.createServer(function (request, response){
    response.writeHead(200,  {'Content-Type':  'text/html;  charset=utf-8'});
    if(request.url !== "/favicon.ico"){//清除第2次访问
        var pathname = url.parse(request.url).pathname;
        console.log(pathname);
        pathname = pathname.replace(/\//,'');//替换掉前面的'/'
        console.log(pathname);
        router[pathname](request, response);
        response.end('结束');
    }
}).listen(8000);
console.log('Server running at http://127.0.0.1:8000/');

 

router.js

module.exports={
    login:function(req,res){
        res.write("我是login方法");
    },
    register:function(req,res){
        res.write("我是register方法");
    }

}

 

报错:

TypeError: router[pathname] is not a function
    at Server.<anonymous> (F:\Project\NoodeJsProject\study\rout.js:12:25)
    at emitTwo (events.js:125:13)
    at Server.emit (events.js:213:7)
    at parserOnIncoming (_http_server.js:602:12)
    at HTTPParser.parserOnHeadersComplete (_http_common.js:116:23)

分析:

不要直接访问http://127.0.0.1:8000,不然会报这个错误,要这样http://127.0.0.1:8000/login访问就正常了。

 

posted @ 2017-09-30 11:05  嘆世殘者——華帥  阅读(781)  评论(0编辑  收藏  举报