Express基于Node.js的Web开发框架 --笔记

血红的双手。 提交于 2019-12-10 23:21:56

从学Node.js语法开始,到Node.js的Web开发相关内容:再到引入Express框架,似乎理解了底层源码之后,再来看Express框架,似乎就很简单啦。
Node.js的Web开发相关内容:

  1. Node.js 不需要依赖第三方应用软件(Apache) 可以基于API自己去实现
  2. 实现静态资源服务器
  3. 路由处理
  4. 动态路由
  5. 模板引擎
  6. get和post参数的处理

也许就是为了开发的方便,从而诞生了Express框架,要是基于Node.js去托管一个静态的网页的话,也许需要这么写

const fs = require('fs');
const path = require('path')
const mime = require('./mime.json')
exports.staticServer = (req,res, root) => {
    fs.readFile(path.join(root,req.url),'utf8', (err, fileContent) => {
        if(err){
            res.writeHead(500,{
                "Content-Type" : "text/plain;charset=utf8"
            })
            res.end("请求的页面不存在")
        }else{
            let ext = path.extname(req.url);
            let dtype = mime[ext] || 'text/html';
            if(dtype.startsWith('text')){
                dtype += ';charset=utf8';
            }
            res.writeHead(200,{
                "Content-Type" : dtype
            })
            res.end(fileContent);
        }
    })
}
```js

搭建一个动态的服务器还需要模板引擎(art-template):

```js
const http = require('http')
const ss = require('./06.js');
const url = require('url')
const querystring = require("querystring")
const path = require('path')
http.createServer((req, res) => {
    // 启动静态资源

    // if(req.url.startsWith('/www')){
    //     ss.staticServer(req,res,__dirname);
    // }
    // 
    ss.staticServer(req,res,path.join(__dirname));  // 托管静态的网页
    // 动态资源
    if(req.url.startsWith('/login')){
        if(req.method == 'GET'){
            let param = url.parse(req.url, true).query;
            res.writeHead(200,{
                "Content-Type" : "text/plain;charset=utf8"
            })
            if(param.username == 'admin' && param.password == '123'){
                
                res.end("GET验证成功!")
            }else{
                res.end("GET验证失败")
            }
        }
        if(req.method == "POST"){
            let pdata = '';
            req.on('data',(chunk)=>{
                pdata += chunk;
            })
            req.on('end',()=>{
                let obj = querystring.parse(pdata);
                res.writeHead(200,{
                    "Content-Type" : "text/plain;charset=utf8"
                })
                if(obj.username == 'admin' && obj.password == '123'){
                    res.end("登入成功");
                }else{
                    res.end("POST 验证失败")
                }
            })
        }
    }
}).listen(3005,()=>{
    console.log("running");
})

所以Express框架的出现,改善了这个现状。

const express = require('express')
const app = express()

// 监听的路径是‘/‘
app.get('/Home', (req, res) => {
    res.send("OK!");
}).listen(3000, () => {
    console.log("running....");
})
app.use(express.static('public'));
app.use(express.static('myexpress'));

完美的封装了一个基于Node.js的

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!