剧场模式
首页后端Nodejs轻松学 nodejs - 基础篇

轻松学 Node.js - 基础篇 #14 web 服务器 part 6 重构路由代码

海外散仙厉飞雨 · 真仙发布于

注意:

404页面这个部分不对,它的状态码应该是 404,而不是 200(疏忽之处,请各位看官自行修正)

app.js

var server = require('./server');
var router = require('./router');
var handler = require('./handler');

var handle = {};
handle["/"] = handler.home;
handle['/home'] = handler.home;
handle['/review'] = handler.review;
handle['/api/v1/records'] = handler.api_records;

server.startServer(router.route, handle);

server.js

var http = require('http');
var fs = require('fs');

function startServer(route, handle) {
    var onRequest = function(request, response) {
        console.log('Request received ' + request.url);
        route(handle, request.url, response);
    }

    var server = http.createServer(onRequest);

    server.listen(3000, '127.0.0.1');
    console.log('Server started on localhost port 3000');
}

module.exports.startServer = startServer;

router.js

var fs = require('fs');

function route(handle, pathname, response) {
    console.log('Routing a request for ' + pathname);
    if (typeof handle[pathname] === 'function') {
        handle[pathname](response);
    } else {
        response.writeHead(200, { 'Content-Type': 'text/html' });
        fs.createReadStream(__dirname + '/404.html', 'utf8').pipe(response);
    }
}

module.exports.route = route;

handler.js

var fs = require('fs');

function home(response) {
    response.writeHead(200, { 'Content-Type': 'text/html' });
    fs.createReadStream(__dirname + '/index.html', 'utf8').pipe(response);
}

function review(response) {
    response.writeHead(200, { 'Content-Type': 'text/html' });
    fs.createReadStream(__dirname + '/review.html', 'utf8').pipe(response);
}

function api_records(response) {
    response.writeHead(200, { 'Content-Type': 'application/json' });
    var jsonObj = {
        name: "hfpp2012"
    };
    response.end(JSON.stringify(jsonObj));
}

module.exports = {
    home: home,
    review: review,
    api_records: api_records
}
17 条回复
学员
与UIuoi89898 · 道祖huang-guanhua · 真仙liaokui · 真仙qiaochunmei · 真仙qianduan · 真仙Geassu · 道祖lihoubai · 真仙496087321 · 真仙mike652638 · 真仙zbx7858 · 道祖
最新动态
与UIuoi89898 · 道祖学习到了7:39
huang-guanhua · 真仙学习到了10:07
liaokui · 真仙学习到了10:00
qiaochunmei · 真仙学习到了10:09
qianduan · 真仙学习到了0:00

© 汕尾市求知科技有限公司 | 粤ICP备19038915号 | 在线学员:44

Top