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>