首页 > 代码库 > node.js如何处理请求的路由

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

 

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如何处理请求的路由