nodejs5: 静态web服务器、ejs

1 路由

文件结构:
在这里插入图片描述

// app.js
const http = require('http');
const routes = require('./module/routes');
const url = require('url');

http.createServer(function (req, res) {
    // 创建静态web服务
    routes.static(req, res, 'my_website');
    // 路由
    let pathname = url.parse(req.url).pathname;
    if (pathname == '/login') {
        res.writeHead(200, { 'Content-Type': 'text/html; charset="utf-8"' });
        res.end("执行登录");
    } else if (pathname == '/register') {
        res.writeHead(200, { 'Content-Type': 'text/html; charset="utf-8"' });
        res.end("执行注册");
    } else if (pathname == '/admin') {
        res.writeHead(200, { 'Content-Type': 'text/html; charset="utf-8"' });
        res.end("后台逻辑");
    } else {
        res.writeHead(200, { 'Content-Type': 'text/html; charset="utf-8"' });
        res.end('404 NOT FOUND, 页面走丢了');
    }

}).listen(8081);

console.log('Server running at http://127.0.0.1:8081/');
//routes.js
const fs = require('fs');
const path = require('path');
const url = require('url');

let getFileMime = function (extname) {
    let data = fs.readFileSync('./data/mime.json');
    let mimeObj = JSON.parse(data.toString());
    return mimeObj[extname];
}

exports.static = function (req, res, staticPath) {
    // 1. 获取地址
    let pathname = url.parse(req.url).pathname;
    pathname = pathname=='/'?'/index.html':pathname;
    let extname = path.extname(pathname);
    // 2. 通过fs模块读取文件
    if (pathname != '/favicon.ico') {
        // 同步方法
        try {
            let data = fs.readFileSync('./' + staticPath + pathname);
            if (data) {
                let mime = getFileMime(extname);
                // console.log('  -' + extname + ' ' + mime);
                res.writeHead(200, { 'Content-Type': '' + mime + ';charset="utf-8"' });
                res.end(data);
            }
        } catch (err) {

        }
        // 异步方法,在app.js没有使用路由时可以使用
        // console.log('pathname' + pathname);
        // fs.readFile('./' + staticPath + pathname, (err, data) => {
        //     if (err) {
        //         res.writeHead(404, { 'Content-Type': 'text/html; charset="utf-8"' });
        //         res.end('404 NOT FOUND, 页面走丢了');
        //         return;
        //     }
        //     console.log(data);
        //     if (data) {
        //         let mime = getFileMime(extname);
        //         console.log('  -' + extname + ' ' + mime);
        //         res.writeHead(200, { 'Content-Type': '' + mime + ' ;charset="utf-8"' });
        //         res.end(data);
        //     }
        // })
    }
}

调了一下午的bug,因为写http头的时候忘记在content-type和 charset之间加分号。

2 ejs

//app.js
...
    if (pathname == '/login') {
        let msg = '这是一个数据';
        let list = [
            {
                title: "新闻1",
            },
            {
                title: "新闻2",
            },
            {
                title: "新闻3",
            }
        ];
        ejs.renderFile('./views/login.ejs', {
            msg: msg, 
            newslist: list
        }, (err, data) => {
            res.writeHead(200, { 'Content-Type': 'text/html; charset="utf-8"' });
            res.end(data);
        })
    }
...

./view/login.ejs

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ejs-login</title>
</head>
<body>
    <h2>这是一个登陆页面</h2>
    <h3><%=msg%></h3>
    <br>
    <ul>
        <%for(var i = 0; i < newslist.length; ++i){%>
            <li><%=newslist[i].title%></li>
        <%}%>
    </ul>
</body>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值