所谓路由就是 web 服务器会根据用户输入的不同 url(实际是 path 不同, domain 是相同的, 包括协议, host, port)返回不同的页面.
例如登录页面 login 和注册页面 register
- # 默认端口为 80
- http://localhost/login #login 页面
- http://localhost/register #register 页面
实现思路
1. 第一步要得到用户请求的 url
可以通过监听函数中的 request 参数获取, 即 request.url
2. 解析 url, 得到具体的请求页面, 也就是路由入, login 和 register
获取 url 之后, 利用标准模块'url'中的 parse 函数提取出路由
首先看一下 url.parse( )函数的功能, 例如调用 url.parse(http://localhost/login)的结果如下所示
- Url {
- protocol: 'http:',
- slashes: true,
- auth: null,
- host: 'localhost',
- port: null,
- hostname: 'localhost',
- hash: null,
- search: null,
- query: null,
- pathname: '/login',
- path: '/login',
- href: 'http://localhost/login'
- }
获得的是一个 url 对象, 可以提取出各部分的内容, 所以路由信息可以提取为
var pathname = url.parse(request.url).pathname;
但是我们还需要将'/'去掉
pathname = pathname.replace(/\//,'')// 去掉'/'
3. 编写路由器, 路由器就是若干个返回不同页面的函数集合, 路由器根据不同的路由信息调用不同的函数, 返回不同的页面.
- //------------router.JS-------------------------
- module.exports = {
- login:function(req, res) {
- res.writeHead(200,{'Content-type':'text/html,charset=utf-8'})
- res.write('Login page')
- res.end()
- },
- register:function(req, res) {
- res.writeHead(200,{'Content-type':'text/html,charset=utf-8'})
- res.write('Register page')
- res.end()
- }
- }
主函数入下, 则可实现根据不同的路由 (pathname) 调用不同的路由函数, 返回不同的页面.
- //------------main.JS---------------------
- var http = require('http');
- var functions=require('./models/functions.js')
- var router=require('./router')
- var url = require('url')
- http.createServer(function(request, response) {
- var pathname = url.parse(request.url).pathname;
- pathname = pathname.replace(/\//,'')// 去掉'/'
- console.log(pathname)
- router[pathname](request, response)
- }).listen(80);
- console.log('Server is running at 127.0.1.1:80')
异常 (例外) 处理
就咱们的这个例子来说只在 router 里面定义了连个函数 login 和 register, 如果用户请求其他的页面, Web 服务会直接崩溃, 这不是我们希望看到的, 所以要提供例外来处理用户的其他我们没有定义的请求页面. 实现很简答, 只是将 router[pathname](request, response)包进 try...catch 块中, 在 catch 中对异常进行妥善处理
- try {
- router[pathname](request, response)
- }catch(err) {
- response.writeHead(200,{'Content-Type':'text/html,charset=utf-8'});
- response.write(err.toString())
- response.end()
- }
这样即使用户输入千奇百怪的 url, Web 服务也不会崩溃, 只会在前端显示错误信息提示用户.
来源: http://www.css88.com/qa/node-js/14619.html