Nodejs基础、Nodejs打在一个类似Express的框架、MongoDb的基础、Nodejs操作Mongodb、Koa2入门实战。从0到1学会Nodejs入门教程
Koajs入门视频教程在线学习地址:https://www.bilibili.com/video/BV1xm4y1c7zr/?p=1
Koajs入门视频教程网盘下载地址:https://pan.baidu.com/s/1QN_XkXRXmIw6V7HevntBQQ 提取码:abcd
Express是一个nodejs的web开源框架,用于快速的搭建web项目。其主要集成了web的http服务器的创建、静态文本管理、服务器URL地址请求处理、get和post请求处理分发、session处理等功能。
1.新建一个express-route.js的文件写入下面代码
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._post['dologin'](req,res)
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;
}
// /login/
G._post[string]=callback;
//G._post['dologin']=function(req,res){
//
//}
}
return app;
}
module.exports=Server();
2.在对应的页面配置路由:
/**
* Created by Administrator on 2017/7/8 0008.
*/
var http=require('http');
var url=require('url');
var G={};
//定义方法开始结束
var app=function(req,res){
//console.log('app'+req);
var pathname=url.parse(req.url).pathname;
if(!pathname.endsWith('/')){
pathname=pathname+'/';
}
if(G[pathname]){
G[pathname](req,res); /*执行注册的方法*/
}else{
res.end('no router');
}
}
//定义一个get方法
app.get=function(string,callback){
if(!string.endsWith('/')){
string=string+'/';
}
if(!string.startsWith('/')){
string='/'+string;
}
// /login/
G[string]=callback;
//注册方法
//G['login']=function(req,res){
//
//}
}
//只有有请求 就会触发app这个方法
http.createServer(app).listen(3000);
//注册login这个路由(方法)
app.get('login',function(req,res){
console.log('login');
res.end('login');
})
app.get('register',function(req,res){
console.log('register');
res.end('register');
})