码迷,mamicode.com
首页 > Web开发 > 详细

node routes.js

时间:2021-04-07 10:47:38      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:ryu   格式   console   too   ejs   ==   let   后缀名   dex   

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;

node routes.js

标签:ryu   格式   console   too   ejs   ==   let   后缀名   dex   

原文地址:https://www.cnblogs.com/zhaofeis/p/14618625.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!