1、实现一个简单的路由请求

创建目录如下:
image.png

index.js代码:

  1. var server = require("./server");
  2. var router = require("./router");
  3. var requestHandlers = require('./requestHandlers')
  4. var handle = {}
  5. handle["/"] = requestHandlers.start;
  6. handle["/start"] = requestHandlers.start;
  7. handle["/upload"] = requestHandlers.upload;
  8. server.start(router.route, handle);

server.js代码:

  1. var http = require("http");
  2. var url = require("url");
  3. function start(route, handle) {
  4. function onRequest(request, response) {
  5. var pathname = url.parse(request.url).pathname;
  6. response.writeHead(200, { "Content-Type": "text/plain" });
  7. var content = route(handle, pathname);
  8. response.write(content);
  9. response.end();
  10. }
  11. http.createServer(onRequest).listen(8888,() => {
  12. console.log("Server has started 8888.");
  13. });
  14. }
  15. exports.start = start;

router.js代码:

  1. function route(handle, pathname) {
  2. if (typeof handle[pathname] === 'function') {
  3. return handle[pathname]();
  4. } else {
  5. return "404 Not found";
  6. }
  7. }
  8. exports.route = route;

requestHandlers.js代码:

  1. function start() {
  2. return "Hello Start";
  3. }
  4. function upload() {
  5. return "Hello Upload";
  6. }
  7. exports.start = start;
  8. exports.upload = upload;

实现效果:
image.png
image.png