路由器未定义Node.js

时间:2017-06-07 08:21:49

标签: javascript node.js

我是Node.js的新手,我正在尝试创建一个HTTP服务器,但出于某种原因,当我尝试将路由器用于购买URL请求时,它不起作用。

我的代码:

Server.js

 class Person {
        private String name;
        private int age;
        public Person(String name, int age) {
            this.name = name;
            this.age = age;
        }
    }

    public class Main {
        public static void main(String[] args) {
            Person[] per = new Person[]{new Person("Simon", 20), new Person("John", 21), new Person("Willy", 22)};
        }
    }

Index.js

var url = require("url");
var http = require("http"); 


function start() {
function onRequest(request, response) { 
    var pathname = url.parse(request.url).pathname; 
    console.log("Request received.");       

    route(pathname);

    response.writeHead(200, {"Content-Type" : "text/plain"});
    response.write("Hello World");
    response.end();
}

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

exports.start = start;

Router.js

var server = require("./server");
var router = require("./router");

server.start(router.route);

当尝试通过Node.js启动服务器时,它会显示以下错误:

  

未定义路线

     
    

路线(路径);

  

我该如何做到这一点?

1 个答案:

答案 0 :(得分:3)

您已将route传递给start函数,但未定义参数,您需要添加一个。

function start(route) {
    function onRequest(request, response) {
        var pathname = url.parse(request.url).pathname;
        console.log("Request received.");

        route(pathname);

        response.writeHead(200, {
            "Content-Type": "text/plain"
        });
        response.write("Hello World");
        response.end();
    }

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