最近学习的 Node.js 之 http

Posted FHBIAO

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了最近学习的 Node.js 之 http相关的知识,希望对你有一定的参考价值。

利用 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的主要内容,如果未能解决你的问题,请参考以下文章

Node.js之文件下载

node.js学习笔记之读文件

node.js学习笔记之_读文件

node.js学习笔记之调用函数

Node.js之路径切换小案例

Node.js学习心得