const http = require('http');
const url = require('url');
http.createServer((req, res) => {
const pathName = url.parse(req.url).pathname;
if (['/actors', '/actresses'].includes(pathName)) {
res.writeHead(200, {
'Content-Type': 'text/html'
});
const actors = ['Leonardo DiCaprio', 'Brad Pitt', 'Johnny Depp'];
const actresses = ['Jennifer Aniston', 'Scarlett Johansson', 'Kate Winslet'];
let lists = [];
if (pathName === '/actors') {
lists = actors;
} else {
lists = actresses;
}
const content = lists.reduce((template, item, index) => {
return template + `<p>No.${index+1} ${item}</p>`;
}, `<h1>${pathName.slice(1)}</h1>`);
res.end(content);
} else {
res.writeHead(404);
res.end('<h1>Requested page not found.</h1>')
}
}).listen(9527);
-- server.js -- lib -- router.js -- views -- controllers -- models
const http = require('http');
const router = require('./lib/router')();
router.get('/actors', (req, res) => {
res.end('Leonardo DiCaprio, Brad Pitt, Johnny Depp');
});
http.createServer(router).listen(9527, err => {
if (err) {
console.error(err);
console.info('Failed to start server');
} else {
console.info(`Server started`);
}
});
const router = require('./lib/router')();
const actorsController = require('./controllers/actors');
router.use((req, res, next) => {
console.info('New request arrived');
next()
});
router.get('/actors', (req, res) => {
actorsController.fetchList();
});
router.post('/actors/:name', (req, res) => {
actorsController.createNewActor();
});
router.use(fn);
router.use((req, res, next) => {
console.info('New request arrived');
next()
});
router.HTTP_METHOD(path, fn)
const METHODS = ['GET', 'POST', 'PUT', 'DELETE', 'HEAD', 'OPTIONS'];
module.exports = () => {
const routes = [];
const router = (req, res) => {
};
router.use = (fn) => {
routes.push({
method: null,
path: null,
handler: fn
});
};
METHODS.forEach(item => {
const method = item.toLowerCase();
router[method] = (path, fn) => {
routes.push({
method,
path,
handler: fn
});
};
});
};
const router = (req, res) => {
const pathname = decodeURI(url.parse(req.url).pathname);
const method = req.method.toLowerCase();
let i = 0;
const next = () => {
route = routes[i++];
if (!route) return;
const routeForAllRequest = !route.method && !route.path;
if (routeForAllRequest || (route.method === method && pathname === route.path)) {
route.handler(req, res, next);
} else {
next();
}
}
next();
};
router.use((req, res, next) => {
console.info('New request arrived');
next()
});
router.get('/actors', (req, res) => {
res.end('Leonardo DiCaprio, Brad Pitt, Johnny Depp');
});
router.get('/actresses', (req, res) => {
res.end('Jennifer Aniston, Scarlett Johansson, Kate Winslet');
});
router.use((req, res, next) => {
res.statusCode = 404;
res.end();
});
router.all = (path, fn) => {
METHODS.forEach(item => {
const method = item.toLowerCase();
router[method](path, fn);
})
};
const defaultErrorHander = (err, req, res) => {
res.statusCode = 500;
res.end();
};
module.exports = (errorHander) => {
const routes = [];
const router = (req, res) => {
...
errorHander = errorHander || defaultErrorHander;
const next = (err) => {
if (err) return errorHander(err, req, res);
...
}
next();
};
...
const router = require('./lib/router')((err, req, res) => {
console.error(err);
res.statusCode = 500;
res.end(err.stack);
});
...
router.use((req, res, next) => {
console.info('New request arrived');
next(new Error('an error'));
});
[code]localhost:9527/actors/Leonardo[/code]与
[code]router.get('/actors/:name', someRouteHandler);[/code]
这条route应该匹配成功才是。
新增一个函数用来将字符串类型的 route.path 转换成正则对象,并存入 route.pattern:
const getRoutePattern = pathname => {
pathname = '^' + pathname.replace(/(\:\w+)/g, '\(\[a-zA-Z0-9-\]\+\\s\)') + '$';
return new RegExp(pathname);
};
const matchedResults = pathname.match(route.pattern);
if (route.method === method && matchedResults) {
addParamsToRequest(req, route.path, matchedResults);
route.handler(req, res, next);
} else {
next();
}
const addParamsToRequest = (req, routePath, matchedResults) => {
req.params = {};
let urlParameterNames = routePath.match(/:(\w+)/g);
if (urlParameterNames) {
for (let i=0; i < urlParameterNames.length; i++) {
req.params[urlParameterNames[i].slice(1)] = matchedResults[i + 1];
}
}
}
router.get('/actors/:year/:country', (req, res) => {
res.end(`year: ${req.params.year} country: ${req.params.country}`);
});
...
const actorsController = require('./controllers/actors');
...
router.get('/actors', (req, res) => {
actorsController.getList(req, res);
});
router.get('/actors/:name', (req, res) => {
actorsController.getActorByName(req, res);
});
router.get('/actors/:year/:country', (req, res) => {
actorsController.getActorsByYearAndCountry(req, res);
});
...
const actorsTemplate = require('../views/actors-list');
const actorsModel = require('../models/actors');
exports.getList = (req, res) => {
const data = actorsModel.getList();
const htmlStr = actorsTemplate.build(data);
res.writeHead(200, {
'Content-Type': 'text/html'
});
res.end(htmlStr);
};
exports.getActorByName = (req, res) => {
const data = actorsModel.getActorByName(req.params.name);
const htmlStr = actorsTemplate.build(data);
res.writeHead(200, {
'Content-Type': 'text/html'
});
res.end(htmlStr);
};
exports.getActorsByYearAndCountry = (req, res) => {
const data = actorsModel.getActorsByYearAndCountry(req.params.year, req.params.country);
const htmlStr = actorsTemplate.build(data);
res.writeHead(200, {
'Content-Type': 'text/html'
});
res.end(htmlStr);
};
[
{
"name": "Leonardo DiCaprio",
"birth year": 1974,
"country": "US",
"movies": ["Titanic", "The Revenant", "Inception"]
},
{
"name": "Brad Pitt",
"birth year": 1963,
"country": "US",
"movies": ["Fight Club", "Inglourious Basterd", "Mr. & Mrs. Smith"]
},
{
"name": "Johnny Depp",
"birth year": 1963,
"country": "US",
"movies": ["Edward Scissorhands", "Black Mass", "The Lone Ranger"]
}
]
const actors = require('./test-data');
exports.getList = () => actors;
exports.getActorByName = (name) => actors.filter(actor => {
return actor.name == name;
});
exports.getActorsByYearAndCountry = (year, country) => actors.filter(actor => {
return actor["birth year"] == year && actor.country == country;
});
const actorTemplate = `
<h1>{name}</h1>
<p><em>Born: </em>{contry}, {year}</p>
<ul>{movies}</ul>
`;
exports.build = list => {
let content = '';
list.forEach(actor => {
content += actorTemplate.replace('{name}', actor.name)
.replace('{contry}', actor.country)
.replace('{year}', actor["birth year"])
.replace('{movies}', actor.movies.reduce((moviesHTML, movieName) => {
return moviesHTML + `<li>${movieName}</li>`
}, ''));
});
return content;
};
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有