node routes.js

let path = require('path');
let url = require('url');
let fs = require('fs');
let ejs = require('ejs');

let tools = require('./tools');

let routes = {
'static': (request, response) => {
// 有些地址后面会有传值 列入/index.html?12324123
// url.parse(request.url).pathname url.parse().pathname去掉request.url后面的传值
let queryUrl = url.parse(request.url).pathname === '/' ? '/index.html' : url.parse(request.url).pathname;
// extname 获取文件的后缀名(格式名)
let extname = path.extname(queryUrl);

if(queryUrl !== '/favicon.ico') {
// 静态服务器
let localUrl = '';
if (extname === '.html') {
if (queryUrl === '/index.html') {
localUrl = '/index.html';
} else {
localUrl = '/pages' + queryUrl;
}
} else {
localUrl = '.' + queryUrl;
}

try {
let data = fs.readFileSync(localUrl);
if (data) {
// 设置响应头
response.writeHead(200,{'Content-Type': `${tools['contentType'][extname]};charset="utf-8"`});
response.end(data);
}
} catch (e) {

}
}
},

'route': {
'index': (request, response, data) => {
console.log(1321);
console.log(data);
ejs.renderFile('./index.html', {'list': data, 'msg': '我是ejs'}, (err, data) => {
response.writeHead(200,{'Content-Type': `text/html;charset="utf-8"`});
response.end(data);
});
},
'text': (request, response, data) => {

},
'error': (request, response, data) => {
response.writeHead(200,{'Content-Type': `text/html;charset="utf-8"`});
response.end('404 找不到地址');
},
}
}


module.exports = routes;
上一篇:前端 JS 原生 javascript 和 location.hash 实现一个单页应用的路由 router


下一篇:python-无法获取django声明的应用程序路由作为页面