一、關于POST請求
post方法作為http請求很重要的一部分,幾乎所有的網站都有用到它,與get不同,post請求更像是在服務器上做修改操作,它一般用于數據資源的更新。
相比于get請求,post所請求的數據會更加安全。上一章中我們發(fā)現get請求會在地址欄顯示輸入的用戶名和密碼(有中文時會轉化為BASE64加密),而post請求則會將數據放入http包的包體中,這使得別人無法直接看到用戶名和密碼!
二、Express如何設置POST請求
1.我們的知道,首先我們得知道在form表單進行post請求,enctype屬性一般設置為“application/x-www-form-urlencoded”,如果設置成multipart/form-data,則多用于文件上傳,如下:
<form action="#" method="post" enctype="application/x-www-form-urlencoded">
</form>
之后,我們可以使用npm提供的body-parser或者connect-multiparty來獲取post數據。我也會把兩種方式都進行演示:
(1)、body-parser
Express中默認都使用body-parser作為請求體解析post數據,這個模塊也能解析:JSON、Raw、文本、URL-encoded格式的請求體。
首先在項目目錄安裝body-parser:
cnpm install body-parser --save
在項目app.js中,引用和設置該模塊:
const bodyParser=require("body-parser");
// 解析以 application/json 和 application/x-www-form-urlencoded 提交的數據
var jsonParser = bodyParser.json();
var urlencodedParser = bodyParser.urlencoded({ extended: false });
bodyParser.json()很明顯是將json作為消息主題,再且常見的語言和瀏覽器大都支持json規(guī)范,使得json處理起來不會遇上兼容性問題。
application/x-www-form-urlencoded:
如果form表單不設置enctype屬性,那么他默認就會是這種。
之后獲取數據:
app.post("/",urlencodedParser,function(req,res){
? ? res.send(req.body);
? ? });
在中間添加urlencodedParser,請求是依然使用req.body獲取數據。
下面是一個完整的實例:
index.html:
<!DOCTYPE html>
<html>
? ? <head>
? ? ? ? <meta charset="utf-8">
? ? ? ? <title></title>
? ? </head>
? ??<body>
? ? ? ? <form action="http://localhost:8080/" method="post" enctype="application/x-www-form-urlencoded">
? ? ? ? ? ? 用戶:
? ? ? ? ? ? <input type="text" name="user" id="user" placeholder="用戶名"><br>
? ? ? ? ? ? 密碼:
? ? ? ? ? ? <input type="password" name="password" id="password" placeholder="密碼"/><br>
? ? ? ? ? ? <input type="submit" value="提交"/>
? ? ? ? </form>
? ? </body>
</html>
app.js:
const express=require("express");
const bodyParser=require("body-parser");
var app=express();
// 解析application/json數據
var jsonParser = bodyParser.json();
// 解析application/x-www-form-urlencoded數據
var urlencodedParser = bodyParser.urlencoded({ extended: false });
app.post('/',urlencodedParser,function(req,res){
res.send(req.body);
});
app.listen(8080);
(2)、connect-multiparty
雖然connect-multiparty多用于文件上傳,但也可以訪問到post請求的數據,先安裝
cnpm install connect-multiparty --save
再引入和構建函數:
const multipart = require('connect-multiparty');
var multipartMiddleware = multipart();
同樣我們也采用req.body來獲取參數:
app.post('/',multipartMiddleware,function(req,res){
res.send(req.body);
});
完整的:
const express=require("express");
const multipart = require('connect-multiparty');
var multipartMiddleware = multipart();
var app=express();
app.post('/',multipartMiddleware,function(req,res){
res.send(req.body);
});
app.listen(8080);
相比于body-parser,代碼量似乎更少一些,但我還是建議使用body-parser,根據官方說法,他會在服務器上創(chuàng)建臨時文件,并且永遠不會去清理它們,這會相當兩會系統(tǒng)資源,所以不到萬不得已請不要去使用它。
總結
post數據在網頁開發(fā)時經常使用,請務必掌握它,只有這樣網頁的交互設計才能夠做到游刃有余,今天就到這里,也希望大家以后多多支持。