node.js 针对不同的请求路径(url) 做出不同的响应

来源:互联网 发布:玩gta5nvidia设置优化 编辑:程序博客网 时间:2024/04/30 11:23

边看这个边写的: 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;         };
0 0
原创粉丝点击