request:請求頭(主機地址+請求方式+客戶瀏覽器的一些信息)、消息體(主要是用戶提交上來的數據)
一、屬性:
baseUrl:當前路由掛載的路徑,
hostname:服務器主機名稱
ip:客戶的IP地址
params:提交上來的參數
path:主機名稱後面的資源路徑
protocol:協議名稱
query:get請求的信息
route:app下掛載的路由對象
cookies:客戶端提交上來的cookie,需要cookieParser中間件
body:post提交的數據對象,需要bodyParser中間件
signedCookies:已簽署的cookies (解析時要聲明加密)
app:代表express的application對象
二、方法:
get(field):獲取請求頭中對應名稱的屬性
is(type):判斷是否有指定的mime類型
param(name):獲取指定名稱的參數值
三、文件上傳
第三方中間件:busboy
var http =require("http");
var express = require("express");
var Busboy = require("busboy");
var fs = require("fs");
var app =exrpress();
http.createServer(app);
app.use(express.static(__dirname_"/public"));
app.post("/fileupload",function(req,res){
//通過請求頭信息創建busboy對象
var busboy = new Busboy({headers: req.headers});
//將流鏈接到busboy對象
req.pipe(busboy);
//監聽file事件獲取文件(字段名、文件、文件名、傳輸編碼,mime類型)
busboy.on("file",function(fieldname,file,filename,encoding,mimetype){
var writeStream = fs.createWriteStream("./upload/"+filename);
//讀取數據
file.on("data",function(data){
cosole.log('File['+fieldname+']got'+data.length+'bytes');
writeStream.write(data);//寫入數據
});
//寫入完成
file.on("end",function(){
console.log('File['+fieldname+']Finished');
writeStream.end();//關閉寫入流
})
})
//監聽filed事件獲取字段信息(字段名稱,字段值,字段名稱是否階段,傳輸編碼,mime類型)
busboy.on("field",function(fieldname,val,fieldnameTruncated,ecoding,mimeype){
console.log('Field['+fieldname+']:value:'+val+',fieldameTruncated='+fieldnameTruncated+',valTruncated='+valTrucated);
//監聽完成事件finish
busboy.on('finish',function(){
console.log('form解析完成');
res.writeHead(303,{Connection:'close',Location:'http://www.baidu.com/'});
})
})
})