从学Node.js语法开始,到Node.js的Web开发相关内容:再到引入Express框架,似乎理解了底层源码之后,再来看Express框架,似乎就很简单啦。
Node.js的Web开发相关内容:
- Node.js 不需要依赖第三方应用软件(Apache) 可以基于API自己去实现
- 实现静态资源服务器
- 路由处理
- 动态路由
- 模板引擎
- 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的
来源:CSDN
作者:DayDay_Lee
链接:https://blog.csdn.net/qq_43127921/article/details/103483437