zoukankan      html  css  js  c++  java
  • node.js 针对不同的请求路径(url) 做出不同的响应

    边看这个边写的: http://wenku.baidu.com/link?url=C4yLe-TVH6060u_x4t34H3Ze8tjoL7HjJaKgH-TvHnEYl-T_gAMYwhmrCeM0Ji59WBPSkoEXPTWk8dPIZVpbFg_by_gN6DJNGYfjlFuYxE_

    上篇文章讲到了浏览器中访问 http://127.0.0.1:8888/ 输出 "hello world",  但是实际当中, 用户访问的或许是 http://127.0.0.1:8888/start 异或者 http://127.0.0.1:8888/upload , 那么node.js该如何去针对不同的请求路径(url) 做出不同的响应呢。

    要做的事

    1.构建一个路由模块

    模块作用:提供请求的URL和其他需要的GET及POST参数,随后根据这些数据来执行相应的代码。因此,我们需要查看HTTP请求,从中提取出请求的URL以及GET/POST参数。

    2.构建一个处理请求的程序模块

    模块作用:存放不同的处理程序,和请求的URL相对应

    3.将前面两个模块和http服务器结合起来

    一、构建一个 路由 模块

    新建一个 router.js 写入

    // 路由模块,针对不同的请求,做出不同的响应
    // handle 处理请求方法
    
    function route(handle, pathname) {
        console.log("About to route a request for " + pathname);
    
        // 检查给定的路径对应的请求处理程序是否存在,如果存在的话直接调用相应的函数
        if (typeof handle[pathname] == "function") {
            handle[pathname]();
        } else {
            console.log("No request handler found for " + pathname);
        }
    }
    
    exports.route = route;

    二、构建一个处理请求的程序模块

    新建一个 requestHandlers.js 写入

    // 存放不同的处理程序,和请求的URL相对应
    function start() {
        console.log("Request handler 'start' was called.");
    }
    
    function upload() {
        console.log("Request handler 'upload' was called.");
    }
    
    exports.start = start;
    exports.upload = upload;

    三、将前面两个模块和http服务器结合起来

    路由模块的作用是:提供请求的URL和其他需要的GET及POST参数,随后根据这些数据来执行相应的代码。因此,我们需要查看HTTP请求,从中提取出请求的URL以及GET/POST参数。

    我们需要的所有数据都会包含在request对象中,该对象作为onRequest()回调函数的第一个参数传递。但是为了解析这些数据,我们需要额外的Node.JS模块,它们分别是url和querystring模块。

    在server.js里面分别引入

    url模块:解析url

    querystring模块: 解析GET和 POST请求带的参数 (后面再说)

    修改 server.js

    // 请求(require)一个 nodejs 自带的 http模块
    // 请求(require)一个 nodejs 自带的 url解析模块
    var http = require("http"),
        url = require("url");
    
    // console.log(url);
    
    // 调用 http模块 提供的 createServer函数: 
    // 返回一个对象,这个对象有一个 listen 方法,这个方法带一个数值参数,
    // 指定这个 http 服务器监听的端口号.
    
    function start(route, handle) {
    
        function onRequest(request, response) {
            // 获取请求路径
            var pathname = url.parse(request.url).pathname;
    
            // 关闭nodejs 默认访问 favicon.ico
            if (!pathname.indexOf('/favicon.ico')) {
                return; 
            };
    
            // 收到来自 pathname 的请求
            console.log("Request for " + pathname + " received.");
    
            // 路由器处理
            route(handle, pathname);
    
            // 返回数据
            response.writeHead(200, {"Content-type": "text/plain"});
            response.write("Hello world!");
            response.end();
        }
    
        http.createServer(onRequest).listen(8888);
        console.log("Server has start!");
    }
    
    // 开放接口
    exports.start = start;

    修改 index.js

    var server = require("./server"),
        router = require("./router"),
        requestHandlers = require("./requestHandlers");
    
    // handle 保存不同请求路径对应的处理方法
    var handle = {};
    
    handle["/"] = requestHandlers.start;
    handle["/start"] = requestHandlers.start;
    handle["/upload"] = requestHandlers.upload;
    
    // 传入路由模块方法, 路径处理方法
    server.start(router.route, handle);

    四、测试

    在 command 面板输入 node index.js 

    浏览器访问 http://127.0.0.1:8888/start   command 面板显示

    整个过程中有个插曲,就是我测试的时候 command面板 每次都会输出一次 访问 /favicon.ico 的记录,然后百度得到了屏蔽的方法
    http://cnodejs.org/topic/529be564a6957a0809408cab
    在 server.js 中插入

    // 关闭nodejs 默认访问 favicon.ico
            if (!pathname.indexOf('/favicon.ico')) {
                return; 
            };

     

  • 相关阅读:
    在腾讯云上使用URLOS一键安装Discuz! Q
    共享容器——URLOS最新发布的一项超强功能
    在群晖NAS上运行URLOS之后竟然能安装Discuz! Q!!
    Discuz!Q回归,如何一键安装Discuz!Q
    Docker管理面板-URLOS(易用、高效、强大)
    CentOS下Subversion(SVN)的快速安装与配置
    通过URLOS安装Redis缓存为wordpress网站提速
    5分钟快速安装Redmine项目管理软件
    Python3+HTMLTestRunner+SMTP生成测试报告后发送邮件
    Python3+HTMLTestRunner生成html测试报告时报错HTMLTestRunner.py line 687, in generateReport  self.stream.write(output.encode('utf8'))
  • 原文地址:https://www.cnblogs.com/qiangspecial/p/3595419.html
Copyright © 2011-2022 走看看