Nodejs WEB服務器 靜態文件託管、 GET POST路由 EJS模板引擎(8)

Nodejs 靜態文件託管   

css

2、 路由

  官方解釋:路由(Routing)是由一個 URI(或者叫路徑)和一個特定的 HTTP 方法(GETPOST 等)組成的,html

涉及到應用如何響應客戶端對某個網站節點的訪問。node

  非官方解釋:路由指的就是針對不一樣請求的 URL, 處理不一樣的業務邏輯。 npm

 

 

 

3 路由靜態文件提取

原 `services.js` 代碼json

// 引入模塊
var http = require('http');

// fs 模塊
var fs =require('fs');

// path模塊
var path = require('path');

// url 模塊
var url = require('url');

// 自定義模塊
var mimeModel =require('./model/getmimefromfile.js');

http.createServer(function (req, res) {
    //http://localhost:8001/news.html  /news.html
    //http://localhost:8001/index.html  /index.html
    //css/dmb.bottom.css

    // 只獲取路徑,不攜帶參數
    var pathname =url.parse(req.url).pathname;
    //路由分發
    if (pathname==='/'){
        pathname ='/index.html';
    }

    // 獲取後綴名
    var extname = path.extname(pathname);

    if (pathname!=='/favicon.ico'){ /*過濾請求 favicon.ico*/
        //console.log(pathname);
        //文件操做獲取 static 目錄下的 index.html  文件
        fs.readFile('static'+pathname,function (err, data) {
            if (err){
                console.log('404');
                fs.readFile('static/404.html',function (err, data404) {
                    if (err){
                        console.log(err);
                    }
                    res.writeHead('404',{"Content-Type":"text/html;charset='utf-8'"});
                    res.write(data404);
                    res.end()
                })
            }else{//返回文件
                // 獲取文件類型
                var mine = mimeModel.getMine(fs,extname);
                res.writeHead(200,{"Content-Type":mine+";charset='utf-8'"});
                res.write(data);
                res.end()
            }
        })
    }
    console.log(pathname);
}).listen(8001);

 

提取出 `router.js `文件數組

// fs 模塊
var fs =require('fs');

// path模塊
var path = require('path');

// url 模塊
var url = require('url');

// 私有方法 getMine
= function (fs, extname) { //.html var data = fs.readFileSync('./mime.json'); var Mimes = JSON.parse(data.toString()); return Mimes[extname] || 'text/html'; }; exports.statics= function (req,res,staticpath) { // 只獲取路徑,不攜帶參數 var pathname =url.parse(req.url).pathname; //路由分發 if (pathname==='/'){ pathname ='/index.html'; } // 獲取後綴名 var extname = path.extname(pathname); if (pathname!=='/favicon.ico'){ /*過濾請求 favicon.ico*/ //console.log(pathname); //文件操做獲取 static 目錄下的 index.html 文件 fs.readFile(staticpath+'/'+pathname,function (err, data) { if (err){ console.log('404'); fs.readFile(staticpath+'/404.html',function (err, data404) { if (err){ console.log(err); } res.writeHead('404',{"Content-Type":"text/html;charset='utf-8'"}); res.write(data404); res.end() }) }else{//返回文件 // 獲取文件類型 var mine = getMine(fs,extname); res.writeHead(200,{"Content-Type":mine+";charset='utf-8'"}); res.write(data); res.end() } }) } console.log(pathname); }

 

目錄結構瀏覽器

 

 

 

路由分發邏輯演示app

`services2.js`post

//引入http模塊
var http=require('http');

var url=require('url');
//路由:指的就是針對不一樣請求的 URL,處理不一樣的業務邏輯。
http.createServer(function(req,res){


    var pathname=url.parse(req.url).pathname;

    if(pathname=='/login'){

        res.end('login');

    }else if(pathname=='/register'){

        res.end('register');
    }else if(pathname=='/order'){

        res.end('order');


    }else{

        res.end('index');
    }

}).listen(8001);

 

4 初始 EJS模板引擎

官網 : https://www.npmjs.com/package/ejs網站

 

安裝:

npm install ejs –save / cnpm install ejs --save

EJS 經常使用標籤
<% %>流程控制標籤
<%= %>輸出標籤(原文輸出 HTML 標籤)
<%- %>輸出標籤(HTML 會被瀏覽器解析)

 

nodejs 中使用

ejs.renderFile(filename, data, options, function(err, str){
// str => Rendered HTML string
});

 

渲染實例

`02services2.js`

//引入http模塊
var http=require('http');

var url=require('url');

var ejs=require('ejs');

//路由:指的就是針對不一樣請求的 URL,處理不一樣的業務邏輯。

http.createServer(function (req,res) {
    res.writeHead(200,{"Content-Type":"text/html;charset='utf-8'"});

    var pathname = url.parse(req.url).pathname;
    console.log(pathname);
    if (pathname ==="/login"){
        var data ='你好我是後臺數據';

        var list = ['111','222','333'];

        var rawHtml = '<h2>我是原生的h2標籤</h2>';
        // 把數據渲染到模板上面
        ejs.renderFile('views/login.ejs',
            {
                msg:data,
                list:list,
                raw:rawHtml
            },
            function (err,data) {
            console.log('1');
            res.end(data)
        })
    }

}).listen(8001);

 

`views/login.ejs`

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
</head>
<body>
    <h2>這是一個ejs 後臺模板引擎 -- 登陸</h2>
    <h2><%=msg%></h2>
    <br>
    <hr>
    <ul>
        <!-- for 循環渲染數組 -->
        <% for (var i = 0; i < list.length; i++) { %>
            <li><%=list[i]%></li>
        <%}%>
    </ul>

    <!--    渲染 標籤 字符串-->
    <%-raw%>

</body>
</html>

 

5 get 和 post

 

//引入http模塊
var http=require('http');

var url=require('url');

var ejs=require('ejs');

var fs=require('fs');

//路由:指的就是針對不一樣請求的 URL,處理不一樣的業務邏輯。
http.createServer(function(req,res){
    res.writeHead(200,{"Content-Type":"text/html;charset='utf-8'"});

    //獲取get 仍是post請求
    var method=req.method.toLowerCase();
    //console.log(method);
    var pathname=url.parse(req.url,true).pathname;

    if(pathname==='/login'){  /*顯示登陸頁面*/


        ejs.renderFile('views/form.ejs',{

        },function(err,data){
            res.end(data);
        })}else if(pathname==='/dologin' &&method==='get'){
        //get獲取數據
        console.log(url.parse(req.url,true).query);
        res.end('dologin');
    }else if(pathname==='/dologin' &&method==='post'){
        //post獲取數據
        var postStr ='';
        req.on('data',function (chunk) {
            postStr +=chunk;
        });

        req.on('end',function (err,chunk) {
            console.log(postStr);
            fs.appendFile('login.txt',postStr +'\n',function (err) {
                if (err){
                    console.log(err);
                }
                console.log('寫入文件成功');
            })

        })
    }else{
        res.end('other')
    }
}).listen(8001);
相關文章
相關標籤/搜索