Node.js 路由的实现方法

2019-11-09,,,

我们平时工作中,涉及到后台开发,路由基本上是我们第一个需要建的,路由还是很重要的。

那么,什么是路由呢,通俗点举个例子,一个宾馆前台,来了十位客人,前台会安排十位客人入住,每位客人到达宾馆以后,该去哪个房间,都是通过前台来安排。(别喷我)

在一个域名下,会有很多个可访问的地址,这就是路由。

我们呢,要为路由提供请求的URL和其他需要的GET及POST参数,随后路由需要根据这些数据,来决定执行哪些代码。/
因此,我们要查看HTTP请求,从中提取出来我们需要的URL以及GET/POST参数。
我们需要的这些数据都会包含在request对象中,该对象作为onRequest()回调函数的第一个参数传递。但是为了解析这些数据,我们需要额外的Node.js模块,它们分别是url和querystring模块。

          url.parse(string).query
                      |
      url.parse(string).pathname   |
            |          |
            |          |
           ------ -------------------
http://localhost:8888/start?foo=bar&hello=world
                ---    -----
                 |     |
                 |     |
       querystring.parse(queryString)["foo"]  |
                      |
             querystring.parse(queryString)["hello"]

也可以用querystring模块来解析post请求体中的参数,下面会有代码演示。

现在我们写一段代码,用来找出浏览器请求的URL路径 之前也写到如何用node起serve

我们新建一个server.js 代码如下

// 代码route()方法为第二个创建的router.js那的方法。我们在这里使用
const http = require('http')
const url = require('url')

function start(route){
  function onRequest(request, response) {
    let pathName = url.parse(request.url).pathname // 通过url获取到当前访问路径
    console.log('Request for ' + pathName + 'received.')
    route(pathName,response)
  }
  http.createServer(onRequest).listen(8888)
  console.log('Server has started')
}
exports.start = start

然后创建router.js

// 通过传递过来到pathname,来进行不同的操作,如果是根目录,打印hello world
// 如果是/index 打印 pathname :/index
// 如果是其他 打印404
function route(pathname,response) {
  console.log('About to route a request for ' + pathname)
  response.writeHead(200, {'Content-Type' : 'text/plain'})
  if(pathname == '/') {
    response.write('Hello World')
    response.end()
  }else if(pathname == '/index'){
    response.write('pathname :/index')
    response.end()
  } else {
    response.write('404')
    response.end()
  }
  
}
exports.route = route

真实环境肯定不会这么写,这样写主要是理解路由的工作原理

接下来我们创建index.js 倒入我们写好的两个模块。

const server = require('./server')
const router = require('./router')

server.start(router.route)

调用server下的start方法,把router那的route方法传入进去。整体的逻辑就出来了,通过server.js 创建http服务,通过node内置模块url获取到当前访问路径,在通过router.js 对不同访问路径进行不同对代码操作。

最终我们启动命令行 输入node index.js 随后请求一个url 我们就会看到应用输出相应对信息,这表明我们对HTTP服务器已经在使用路由模块了。并会将请求对路径传递给路由,再由路由进行接下来对操作。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持北冥有鱼。

您可能感兴趣的文章:

  • 初学node.js中实现删除用户路由
  • node.js中路由,中间件,ge请求和post请求的参数详解
  • Node.js自定义实现文件路由功能

《Node.js 路由的实现方法.doc》

下载本文的Word格式文档,以方便收藏与打印。