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

Nodejs根据具体请求路径执行具体操作

时间:2017-01-24 16:18:57      阅读:325      评论:0      收藏:0      [点我收藏+]

标签:nodejs根据具体请求路径执行具体操作

1.处理请求模块(requestHandlers.js)

    function start(){

     console.log("Request handler ‘start‘ was called ");

     return "Hello start";

    }

    

    function upload(){

     console.log("Request handler ‘upload‘ was called ");

     return "Hello Upload";

    }

    

    exports.start = start;

    exports.upload = upload;

2.路由模块(route.js)

    function route(handle,pathname){

     console.log("About to route a request for "+pathname);

     if (typeof handle[pathname] == ‘function‘) {

     return handle[pathname]();

     }else{

     console.log("No request handler found for " + pathname);

     return "404 Not found";

     }

    }

    

    exports.route = route;

3.服务器模块(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;

     if (pathname != "/favicon.ico") {

     console.log("Request for" + pathname + " received");

     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");

    }

    

    exports.start = start;

4.调用相应模块(index.js)

    var server = require("./server");

    var router = require("./route");

    var requestHandlers = require("./requestHandlers");

    

    var handle = {};

    handle["/"] = requestHandlers.start;

    handle["/start"] = requestHandlers.start;

    handle["/upload"] = requestHandlers.upload;

    

    server.start(router.route,handle);

5.执行index.js

    node index.js

    访问:http://localhost:8888/start

    输出结果:

        Hello start

    访问:http://localhost:8888/upload

    输出结果:

        Hello Upload

    访问:http://localhost:8888/other

    输出结果:

        404 Not found


本文出自 “素颜” 博客,请务必保留此出处http://suyanzhu.blog.51cto.com/8050189/1894056

Nodejs根据具体请求路径执行具体操作

标签:nodejs根据具体请求路径执行具体操作

原文地址:http://suyanzhu.blog.51cto.com/8050189/1894056

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