Node.js学习(四)路由系统

207 阅读1分钟

app.js

const server = require("./http");
const router = require("./router");

server.start(router.route);

http.js

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

const start = (route) => {
    const onRequest = (req, res) => {
        const pathname = url.parse(req.url).pathname;
        route(pathname,res);
    };
    http.createServer(onRequest).listen(8080);
    console.log("server has started.");
};

exports.start = start;

router.js

const route = (pathname, res) => {
    console.log("about to route a request for" + pathname);
    if (pathname === "/") {
        res.writeHead(200, {"Content-Type": "text/plain"});
        res.write("Hello World");
        res.end();
    } else if (pathname === "/index/home") {
        res.end('index');
    }else {
        res.end('404');
    }
};
exports.route = route;