nodejs之路由
Posted 小白
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了nodejs之路由相关的知识,希望对你有一定的参考价值。
声明:在写nodejs代码的时候,很多模块可以封装保存起来,以后的项目都会用到。
1、路由模块
![技术图片](/img/jia.gif)
var url=require(‘url‘); //封装方法改变res 绑定res.send() function changeRes(res){ res.send=function(data){ res.writeHead(200,{"Content-Type":"text/html;charset=‘utf-8‘"}); res.end(data); } } //暴露的模块 var Server=function(){ var G=this; /*全局变量*/ //处理get和post请求 this._get={}; this._post={}; var app=function(req,res){ changeRes(res); //获取路由 var pathname=url.parse(req.url).pathname; if(!pathname.endsWith(‘/‘)){ pathname=pathname+‘/‘; } //获取请求的方式 get post var method=req.method.toLowerCase(); if(G[‘_‘+method][pathname]){ if(method==‘post‘){ /*执行post请求*/ var postStr=‘‘; req.on(‘data‘,function(chunk){ postStr+=chunk; }) req.on(‘end‘,function(err,chunk) { req.body=postStr; /*表示拿到post的值*/ G[‘_‘+method][pathname](req,res); /*执行方法*/ }) }else{ /*执行get请求*/ G[‘_‘+method][pathname](req,res); /*执行方法*/ } }else{ res.end(‘no router‘); } } app.get=function(string,callback){ if(!string.endsWith(‘/‘)){ string=string+‘/‘; } if(!string.startsWith(‘/‘)){ string=‘/‘+string; } // /login/ G._get[string]=callback; } app.post=function(string,callback){ if(!string.endsWith(‘/‘)){ string=string+‘/‘; } if(!string.startsWith(‘/‘)){ string=‘/‘+string; } G._post[string]=callback; } return app; } module.exports=Server();
2、直接摘抄,然后创建一个文件运行下面的代码。
var http = require(‘http‘); var app = require(‘./express-route‘); http.createServer(app).listen(‘8001‘); app.get(‘login‘,function (req,res) { console.log(‘login‘); res.end(‘login‘); }) app.get(‘register‘,function (req,res) { console.log(‘register‘); res.end(‘register‘); })
以上是关于nodejs之路由的主要内容,如果未能解决你的问题,请参考以下文章
使用 NodeJS 和 JSDOM/jQuery 从代码片段构建 PHP 页面