1、实现一个简单的路由请求
创建目录如下:
index.js代码:
var server = require("./server");
var router = require("./router");
var requestHandlers = require('./requestHandlers')
var handle = {}
handle["/"] = requestHandlers.start;
handle["/start"] = requestHandlers.start;
handle["/upload"] = requestHandlers.upload;
server.start(router.route, handle);
server.js代码:
var http = require("http");
var url = require("url");
function start(route, handle) {
function onRequest(request, response) {
var pathname = url.parse(request.url).pathname;
response.writeHead(200, { "Content-Type": "text/plain" });
var content = route(handle, pathname);
response.write(content);
response.end();
}
http.createServer(onRequest).listen(8888,() => {
console.log("Server has started 8888.");
});
}
exports.start = start;
router.js代码:
function route(handle, pathname) {
if (typeof handle[pathname] === 'function') {
return handle[pathname]();
} else {
return "404 Not found";
}
}
exports.route = route;
requestHandlers.js代码:
function start() {
return "Hello Start";
}
function upload() {
return "Hello Upload";
}
exports.start = start;
exports.upload = upload;
实现效果: