1. 程式人生 > >最近學習的 Node.js 之 http

最近學習的 Node.js 之 http

span div app 方式 服務 ont res {} pre

利用 http 模塊開始寫簡單的web服務。

模塊:

技術分享圖片
const http=require(‘http‘);
const fs=require(‘fs‘);
const path=require(‘path‘);


function startServer() {
    let onRequest=function (req,res) {
        console.log(‘recived a request.‘);
        res.writeHead(200,{‘Content-Type‘:‘text/html‘});

        let wwwdir= path.resolve(__dirname,‘../www‘);
        // console.log(wwwdir);
        let readStream = fs.createReadStream(wwwdir+‘/bbb.html‘);
        readStream.pipe(res);
    };

    let server=http.createServer(onRequest);
    server.listen(80,‘192.168.1.101‘);
};

exports.startServer = startServer;
技術分享圖片

調用者,APP,使用兩行就開啟了一個簡單的web服務。

let server=require(‘./mod_server‘);

server.startServer();

單文件版路由,響應了幾個不同的頁面:

技術分享圖片
const http = require(‘http‘);
const fs = require(‘fs‘);
const path = require(‘path‘);

let wwwdir = path.resolve(__dirname, ‘../www‘);

let onRequest = function (req, res) {
    console.log(‘recived a request. ‘ + req.url);
    if (req.url === ‘/‘ || req.url === ‘/home‘) {
        res.writeHead(200, {‘Content-Type‘: ‘text/html;charset=UTF-8‘});
        let readStream = fs.createReadStream(wwwdir + ‘/index.html‘);
        readStream.pipe(res);
    } else if (req.url === ‘/about‘) {
        res.writeHead(200, {‘Content-Type‘: ‘text/html;charset=UTF-8‘});
        let readStream = fs.createReadStream(wwwdir + ‘/about.html‘);
        readStream.pipe(res);
    } else if (req.url === ‘/api‘) {
        res.writeHead(200, {‘Content-Type‘: ‘application/json‘});
        let jsonObj = {
            name: "alex",
            email: ‘[email protected]‘,
            age: 32
        };
        // console.log(JSON.parse(jsonStr)); // 反序列化
        res.end(JSON.stringify(jsonObj));
    } else {
        res.writeHead(404, {‘Content-Type‘: "text/html;charset=utf8"});
        res.write(‘抱歉 404 ,你要的頁面沒找到.‘);
    }
    ;
};

let server = http.createServer(onRequest);
server.listen(8001, ‘localhost‘);
技術分享圖片

分開為獨立文件的 web server

一、server.js

技術分享圖片
const http = require(‘http‘);

function startServer(route, handle) {
    let onRequest = function (request, response) {
        console.log(‘Request received ‘ + request.url);
        // 傳遞到 route 函數
        route(handle, request.url, response);
    };

    let server = http.createServer(onRequest);

    server.listen(8001, ‘127.0.0.1‘);
    console.log(‘Server started on 127.0.0.1:8001‘);
}

module.exports.startServer = startServer;
技術分享圖片

二、router.js

技術分享圖片
const fs = require(‘fs‘);
const path = require(‘path‘);

let wwwdir = path.resolve(__dirname, ‘../www‘);

function route(handle, pathname, response) {
    console.log(‘Routing a request for ‘ + pathname);
    // 判斷 handle中是否有對應的 pathname 函數
    if (typeof handle[pathname] === ‘function‘) {
        handle[pathname](response); // response作為參數傳遞到 handle 函數
    } else {
        response.writeHead(404, {‘Content-Type‘: ‘text/html‘});
        fs.createReadStream(wwwdir + ‘/404.html‘, ‘utf8‘).pipe(response);
    }
}

module.exports.route = route;
技術分享圖片

三、handler.js

技術分享圖片
const fs = require(‘fs‘);
const path = require(‘path‘);

let wwwdir = path.resolve(__dirname, ‘../www‘);

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

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

function api_records(response) {
    response.writeHead(200, {‘Content-Type‘: ‘application/json‘});
    let jsonObj = {
        name: "Alex",
        passwd: "123456",
        email: ‘[email protected]‘,
        age: 22
    };
    response.end(JSON.stringify(jsonObj));
}

module.exports = {
    home: home,
    review: review,
    api: api_records
};
技術分享圖片

四、app.js 主程序,模塊方式調用前面的三個文件即可

技術分享圖片
const server = require(‘./server‘);
const router = require(‘./router‘);
const handler = require(‘./handler‘);

let handle = {};
handle["/"] = handler.home;
handle[‘/home‘] = handler.home;
handle[‘/review‘] = handler.review;
handle[‘/api‘] = handler.api;

server.startServer(router.route, handle);
技術分享圖片

最近學習的 Node.js 之 http