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

nodejs路由模块使用

时间:2017-01-24 16:19:35      阅读:365      评论:0      收藏:0      [点我收藏+]

标签:nodejs路由模块使用

  1. 创建路由模块(route.js)

function route(pathname){

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

}


exports.route = route;

创建http服务模块(server.js)var http = require("http");var url = require("url");function start(route){ function onRequest(request,response){ var pathname = url.parse(request.url).pathname; if (pathname != "/favicon.ico") { console.log("Request for" + pathname + " received"); route(pathname); response.writeHead(200,{"Content-Type":"text/plain"}); response.write("Hello world"); response.end(); } } http.createServer(onRequest).listen(8888); console.log("Server has started");}exports.start = start;创建index.js来使用http服务器模块和路由模块var http = require("./server");var router = require("./route");http.start(router.route);执行index.js并查看结果

执行命令:node index.js

访问如下地址:http://localhost:8888/demo

执行结果:

    Server has started

    Request for /demo received

    About to route a request for /demo

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

nodejs路由模块使用

标签:nodejs路由模块使用

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

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