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

node.js如何处理请求的路由

时间:2016-12-18 18:17:18      阅读:194      评论:0      收藏:0      [点我收藏+]

标签:listen   head   nod   not found   require   ext   register   ram   handle   

 

var http = require( ‘http‘ )
var handlePaths = []

/**
 * 初始化路由配置数组
 */
function  initRotute()
{
    handlePaths.push( ‘/‘ )
    handlePaths.push( ‘/login‘ )
    handlePaths.push( ‘/register‘ )
}

/**
 * 处理路由的逻辑
 * @param path
 */
function rotuteHandle( path )
{
    //  遍历路由配置信息
    for ( var i in  handlePaths )
    {
        if(  handlePaths[i] == path )
        {
            console.log( ‘获取到相同的路由信息:‘,handlePaths[i] )
            var rlt =  "request rotute is:" +  handlePaths[i]
            return  rlt
        }
    }
    return ‘404 Not Found‘
}

/**
 *  服务器回掉函数
 * @param request
 * @param response
 */
function onRequest( request, response )
{
    var  requestPath = request.url
    console.log(‘请求的路径是=>‘,requestPath )
    response.writeHead( 200, {
        ‘Content-Type‘:‘text/plain‘
    })
    var  responseContent = rotuteHandle( requestPath )
    response.write( responseContent  )
    response.end()
}

var server =  http.createServer( onRequest )
server.listen( 3000 )
initRotute()
console.log(‘Server is Listening  right now ..‘)

  

node.js如何处理请求的路由

标签:listen   head   nod   not found   require   ext   register   ram   handle   

原文地址:http://www.cnblogs.com/ganchuanpu/p/6194529.html

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