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

轻松学 Node.js - 基础篇 #13 web 服务器 part 5 路由

下载发布于1833 次观看
1

注意:

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

server.js

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

function startServer() {
    var onRequest = function(request, response) {
        console.log('Request received ' + request.url);
        if (request.url === '/' || request.url === '/home') {
            response.writeHead(200, { 'Content-Type': 'text/html' });
            fs.createReadStream(__dirname + '/index.html', 'utf8').pipe(response);
        } else if (request.url === '/review') {
            response.writeHead(200, { 'Content-Type': 'text/html' });
            fs.createReadStream(__dirname + '/review.html', 'utf8').pipe(response);
        } else if (request.url === '/api/v1/records') {
            response.writeHead(200, { 'Content-Type': 'application/json' });
            var jsonObj = {
                name: "hfpp2012"
            };
            response.end(JSON.stringify(jsonObj));
        } else {
            response.writeHead(200, { 'Content-Type': 'text/html' });
            fs.createReadStream(__dirname + '/404.html', 'utf8').pipe(response);
        }
    }

    var server = http.createServer(onRequest);

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

exports.startServer = startServer;

review.html

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    review page
</body>

</html>

404.html

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    404 error page
</body>

</html>
0 条评论
暂无评论~~
扫码打赏 16.8 元起加我微信拉入微信群

加我微信:15014006126

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

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

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

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

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

友情提示
热门播放列表 love