- express()表达式
- express的方法
- express功能分析
一、express()表达式
创建Express应用程序。express()函数是express模块导出的顶级函数。(相当于HTTP.createServer())
let express = require("express");
let app = express();
这个表达会生成一个Application对象,也就是示例中的app,Express框架构建的服务就是由这个对象来管理网络请求与响应。关于Application的具体操作及API在博客的第三部分,在express上还有还有一些静态方法,下面进入第二部分express方法的解析。
二、express的方法
2.1express.json([options]):是Express种的內置中间件功能,它使用body解析器解析请求带有JSON格式的报文主体。
在node原生中获取post请求的请求数据是通过request上的data事件来获取: request.on("data",function(data){console.log(data);}) ,在express中可以使用express.json()引用中间件来处理请求数据,处理后的数据会交给request.body缓存。具体使用如下:
在默认情况下,我们使用 req.body获取到的内容为空对象{},这里需要使用一个中间件body-parser来解析传入的请求主体:
npm install body-parser express --save
创建server.js
1 let express = require("express"); 2 let bodyParser = require('body-parser'); 3 4 let app = express(); 5 6 //基于body-parser中间件注册解析post请求主体中的数据 7 //根据不同的Content-Type分别有以下两种配置 8 app.use(bodyParser.urlencoded());//解析Content-Type为:application/x-www-form-urlencoded的配置 9 app.use(bodyParser.json());//解析Content-Type为:application/json的配置 10 11 app.post("/csJSON",csJSONFun);//配置访问路由,调用csJSONFun处理请求 12 13 app.listen(12306);//配置服务端口 14 15 //将请求的数据(body-parser中间件处理后交给request.body的数据)再发送回客户端 16 function csJSONFun(request,response){ 17 console.log(request.body); 18 response.writeHead(200); 19 response.write(JSON.stringify(request.body)); 20 response.end(); 21 }
客户端测试代码:
1 urlAjaxFun(function(data){ 2 console.log(JSON.parse(data));//{{"APP":"express","text":"cs"}: ""} 3 }); 4 bodyAjaxFun(function(data){ 5 console.log(JSON.parse(data));//{APP: "express", text: "cs"} 6 }); 7 8 function urlAjaxFun(callback){ 9 let xhr = new XMLHttpRequest(); 10 let data = {APP:'express',text:"cs"} 11 xhr.open("POST","/csJSON",true); 12 xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded'); 13 xhr.send(JSON.stringify(data)); 14 xhr.onreadystatechange = function(){ 15 // 监听到readystate=4时 16 // 解析服务器返回的responseText数据 17 if(xhr["readyState"] === 4){ 18 //判断响应状态是否为200--表示请求成功响应 19 if(xhr["status"] === 200){ 20 callback(xhr["responseText"]); 21 } 22 } 23 } 24 } 25 26 function bodyAjaxFun(callback){ 27 let xhr = new XMLHttpRequest(); 28 let data = {APP:'express',text:"cs"} 29 xhr.open("POST","/csJSON",true); 30 xhr.setRequestHeader('Content-type','application/json'); 31 xhr.send(JSON.stringify(data)); 32 xhr.onreadystatechange = function(){ 33 // 监听到readystate=4时 34 // 解析服务器返回的responseText数据 35 if(xhr["readyState"] === 4){ 36 //判断响应状态是否为200--表示请求成功响应 37 if(xhr["status"] === 200){ 38 callback(xhr["responseText"]); 39 } 40 } 41 } 42 }