Post表單提交:
這裏我們首先借助菜鳥網站上的一個post實例說明一下:
var http = require('http');
var querystring = require('querystring');
var postHTML =
'<html><head><meta charset="utf-8"><title>菜鳥教程 Node.js 實例</title></head>' +
'<body>' +
'<form method="post">' +
'網站名: <input name="name"><br>' +
'網站 URL: <input name="url"><br>' +
'<input type="submit">' +
'</form>' +
'</body></html>';
http.createServer(function (req, res) {
var body = "";
req.on('data', function (chunk) {
body += chunk;
});
req.on('end', function () {
// 解析參數
body = querystring.parse(body);
// 設置響應頭部信息及編碼
res.writeHead(200, {'Content-Type': 'text/html; charset=utf8'});
if(body.name && body.url) { // 輸出提交的數據
res.write("網站名:" + body.name);
res.write("<br>");
res.write("網站 URL:" + body.url);
} else { // 輸出表單
res.write(postHTML);
}
res.end();
});
}).listen(3000);
上述的例子中,將html文件通過字符串拼接的形式進行封裝,再通過res.write()打印出來。
但是,倘若html文檔內容很多,則不能採用這種方法。正確的思路應該是:打開並獲取相應的html內容,再將其打印出來。具體步驟如下:
第一步:創建一個index.html文件,如下所示:
<!DOCTYPE html>
<html>
<head>
<title>node</title>
<meta charset="utf-8">
</head>
<body>
<form method="post" action="">
<h2>get發送</h2>
名稱:<input type="text" name="name"><br/>
URL:<input type="test" name="url"><br/>
<input type="submit" name="" value="提交">
</form>
</body>
</html>
方法有很多:
(1)從Stream流中讀取數據
var http = require('http');
var fs = require('fs');
var querystring = require('querystring');
var data='';
var stream=fs.createReadStream('index.html');
stream.on('data',function(chunk){
data+=chunk
})
stream.on('end',function(){//當沒有更多數據可獲取時
http.createServer(onRequest).listen(3000);
console.log("Server has been created!")
})
function onRequest(req,res){
var urlstr="";
//當接收到post請求時,獲取請求的數據
req.on('data', function(chunk){
urlstr+= chunk;
});
//當獲取完所有數據後,對數據參數進行解析
req.on('end', function(){
// 解析參數
urlstr = querystring.parse(urlstr);
console.log(urlstr)//在控制檯中輸出提交的數據
// 設置響應頭部信息及編碼
res.writeHead(200, {'Content-Type': 'text/html; charset=utf8'});
if(urlstr.name && urlstr.url) { // 輸出提交的數據
res.write("網站名:" + urlstr.name);
res.write("<br>");
res.write("網站 URL:" + urlstr.url);
//當沒有可以獲取的數據時,顯示html頁面
}else{ // 輸出表單
res.write(data);
}
res.end();
});
}
(2)readFile讀取數據
fs.readFile('./index.html','utf-8',function(err,d){
data=d
});
主要的方法與上一個例子相同。不同點在於,這裏的data不屬於stream中的數據,可以全局使用。而上一個例子中,如果data最後只能在stream.on('end',function(){})中使用,否則,數據爲空。(3)file文件的方法讀取數據
var http = require('http');
var fs = require('fs');
var querystring = require('querystring');
var buf = new Buffer(1024);
var data="";
fs.open('index.html','r+',function(err,fd){
if (err) {return console.error(err)}
fs.read(fd,buf,0,buf.length,0,function(err,bytes){
if (err) {console.log(err)}
console.log(bytes+'字節被讀取了');
if (bytes>0) {
data=buf.slice(0,bytes).toString()
//console.log(data)
}
});
})
http.createServer(onRequest).listen(3000);
console.log("Server has been created!")
此處利用了Buffer緩存的方式對數據進行讀取.
Get表單提交:
var http=require('http');
var url=require('url');
var util=require('util');
http.createServer(function(req,res){
res.writeHead(200,{'Content-Type':'text/plain;charset=utf-8'})
var params=url.parse(req.url,true);
console.log("網站名: "+params.query.name);
console.log("網站 URL:" + params.query.url);
console.log("search:" + decodeURI(params.search));
res.end(util.inspect(url.parse(req.url,true)));
}).listen(3000);
console.log('createServer is created')
get提交與post提交一個主要的不同點就是,獲取參數的方式不同:
get-->url.parse(req.url,true),這裏獲取到的是一個json對象,可以通過獲取對象屬性的方式得到各項參數
post-->querystring.parse(urlstr),這裏得到的也是json對象
若提交的數據中包含中文字符,則需要利用decodeURLComponent()方法進一步解碼
綜合性實例:
最後,參考一篇文章中的實例,進行了適當修改,給出了下面的綜合性實例。原文參見:http://www.cnblogs.com/leejersey/p/5479012.html
HTML:index.html
<!DOCTYPE html>
<html>
<head>
<title>node</title>
<meta charset="utf-8">
</head>
<body>
<form method="get" action="getlogin">
<h2>get發送</h2>
名稱:<input type="text" name="name"><br/>
URL:<input type="test" name="url"><br/>
<input type="submit" name="" value="提交">
</form>
<form method="post" action="postlogin">
<h2>post發送</h2>
名稱:<input type="text" name="name"><br/>
URL:<input type="test" name="url"><br/>
<input type="submit" name="" value="提交">
</form>
</body>
</html>
Server端
var httpserver = require("http");
var qs = require("querystring");
var url = require("url");
var fs = require("fs");
httpserver.createServer(onRequest).listen(3000);
function onRequest(request,response){
var pathname = url.parse(request.url).pathname;
if(pathname=="/"){//訪問表單頁面
response.writeHead(200,{"Content-Type":"text/html"});
fs.readFile("index.html","utf-8",function(e,data){
response.write(data);
response.end();
});
}else if(pathname=="/postlogin"){//處理post方式請求
var urlstr="";
request.addListener("data",function(postdata){
urlstr+=postdata;//接收到的表單數據字符串,這裏可以用兩種方法將UTF-8編碼轉換爲中文
var jsondata = qs.parse(urlstr);//轉換成json對象
var decodedata = decodeURIComponent(urlstr);//對錶單數據進行解碼
console.log(urlstr);
console.log(jsondata);
console.log(decodedata);
urlstr = decodedata;
});
request.addListener("end",function(){
response.writeHead(200,{"Content-Type":"text/plain; charset=utf-8"});
response.write(urlstr);
response.end();
});
}else if(pathname=="/getlogin"){ //處理get方式請求
var urlstr = url.parse(request.url).query;
var jsondata = qs.parse(urlstr);
var decodedata = decodeURIComponent(urlstr);
console.log(urlstr);
console.log(jsondata);
console.log(decodedata);
urlstr = decodedata;
response.writeHead(200,{"Content-Type":"text/plain; charset=utf-8"});
response.write(urlstr);
response.end();
}else{
response.writeHead(200,{"Content-Type":"text/plain"});
response.write("error");
response.end();
}
}