node.js3
第一部分:express(MVC)
1.下载express
- npm install express --save
2.引入express
require('express')
中间件
- body-parser
- 用于处理函数
- body参数,querystring参数,params路由参数
- urlencoded ({extended:false}),不用querystring处理参数,用qs处理
- qs
3.请求
-
get
-
post
-
put
-
delete
//原生js创建一个ajax请求 //1.创建ajax对象 var xhr = new XMLHttpRequest() /* 调用open方法初始化ajax请求 open(method,url,async) method String 发送ajax请求的方式 get/post/put/delete.. url String ajax请求的路径 async Boolean 是否发起异步的ajax请求 true/false */
4.参数接收
- 路由传参(/😃
- path/:id -->path/2
- 接收方式:req.params
- body传参({})
- path body:
- 接收方式:req.body
- queryString传参(?)
- path?id=2
- 接收方式:req.query
5.静态文件
- app.use(express.static(''))
- 可以多次调用
6.错误页处理
- app.use(function(req,res){
sendfile(error)
});
7.路由
- routes
8.模板
- app.set('view engine','jade')
- app.set('views',path)
ajax补充
//创建xhr对象
var xhr=null;
//浏览器兼容判断
if(window.XMLHttpRequest){
xhr=new XMLHttpRequest();
}else if(window.ActiveXObject){
xhr =new ActiveXObject("Microsoft.XMLHTTP");
}else{
alert("你的浏览器不支持ajax,请升级你的浏览器");
return;
}
//xhr初始化配置
xhr.open("post","/add",true)
//监听xhr对象的状态改变
xhr.onreadystatechange=function(){
//判断xhr对象的状态
if(xhr.readyState===4){
//获取xhr对象返回的信息
alert(xhr.responseText);
}
}