码迷,mamicode.com
首页 > Web开发 > 详细

最近学习的 Node.js 之 http

时间:2018-12-25 17:07:37      阅读:210      评论:0      收藏:0      [点我收藏+]

标签:com   list   out   技术   技术分享   class   node.js   passwd   nbsp   

利用 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: ‘abc@gg.com‘,
            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: ‘aaa@cc.com‘,
        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

标签:com   list   out   技术   技术分享   class   node.js   passwd   nbsp   

原文地址:https://www.cnblogs.com/FHBIAO/p/10174587.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!