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

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

下载发布于1875 次观看
2

注意:

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
}
4 条评论
  • 感谢你的视频,请问;
    请问你视频收到的每个请求为什么没有favicon?我的如下
    receive request/api/catstring
    request path name is /api/catstring
    receive request/favicon.ico
    request path name is /favicon.ico

  • 不用管它,可以忽略,那个是浏览器自己加上的

  • 力挺随风!

  • 多谢

扫码打赏 16.8 元起加我微信拉入微信群

加我微信:15014006126

打赏的朋友或 Pro 学员获得特权

  • 加我微信拉你进微信群,享有更多互动和人脉资源;

  • 网站固定数量代金券,用于购买收费课程;

  • 和 10 年程序员老兵我成为微信好友;

  • 不定期技术分享和视频问题解答

友情提示
热门播放列表 love