node學習筆記(二)(ajax方式向node后台提交數據)


通過ajax向node后台提交數據過程(附手寫前后台代碼),並總結post與get的區別

POST

前台代碼

//CSS簡單給點樣式 
<style>
        form{
            width: 200px;
            height: 200px;
            margin: 100px auto;
        }
        #content{
            width: 400px;
            height: 60px;
            border: 1px solid black;
            margin: auto;
            text-align: center;
            line-height: 60px;
            border-radius: 5px;
        }
        #submit{
            width: 175px;
            height: 30px;
            background-color: skyblue;
            margin: 20px 0;
            border: 1px solid white;
            border-radius: 5px;
        }
    </style>
//HTML
<body>
<div id="content">狀態顯示框</div>
<form action="http://127.0.0.1:8000/from" method="POST"> //post方式
    <label for="login">用戶名:</label><br>
    <input id="login" type="text" name="user" placeholder="請輸入用戶名"><br>  // label for屬性表單綁定
    <label for="login">密碼:</label><br>
    <input id="pwd" type="password" name="pwd" placeholder="請輸入密碼"><br>
    <input id="submit" type="button" value="登錄" onclick="loadXMLDoc()"><br>
</form>
</body>
//JS,ajax
<script>
    function loadXMLDoc(){
        let xhr;
        let username = document.getElementsByName("user")[0];
        let userpwd = document.getElementsByName("pwd")[0];
        xhr = new XMLHttpRequest(); //構造一個ajax對象
        xhr.onreadystatechange=function() {
            if (xhr.readyState==4 && xhr.status==200) {
               document.getElementById("content").innerHTML=xhr.responseText;
              //接收后台數據
            }
        };
        xhr.open("post","http://127.0.0.1:8000/from",true);
        xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");//post必寫請求頭文件
        xhr.send(`user=${a.value}&pwd=${b.value}`);//ES6字符串擴張之模板字符串
    }
</script>
后台代碼
const http = require("http");
const fs = require("fs");
const querystring = require("querystring");
const url = require("url");
//引入需要模塊
let server = http.createServer(function (req,res) {
    let pathname = url.parse(req.url).pathname;
    if(pathname === "/" ){
        fs.readFile("./login.html",function (error,data) {
            if(!error){
                res.writeHead(200,{"content-type":"text/html"});
                res.end(data)
            }else{
                res.end("" + error);
            }
        })
    }else if(pathname === "/from"){
        let data = "";
        req.on("data",function (chunk) {
          //data事件:數據接收時...回調
           data = data + chunk;//chunk參數表示data數據流不斷被解析,不斷發送的數據包,這個例子中數據格式為字符串,只需要一次性接收
           console.log(data)//user=tom&pwd=tom,data流監聽,不斷接收數據流信息
        });
        req.on("end",function () {
          //end事件:數據接收完畢時...回調
            let querys = querystring.parse(data)//將data流轉換為對象形式
            console.log(querys);//{user:"tom",pwd:"tom"}.
            if(querys.user === "tom"  && querys.pwd === "tom"){
                res.writeHead(200,{"content-type":"text/html;charset=utf-8"});//注意報頭文一定要寫
                res.write("登陸成功");
                res.end();
            }else {
                res.writeHead(200,{"content-type":"text/html;charset=utf-8"});
                res.write("登陸失敗");
                res.end();
            }
        })
    }
});
server.listen(8000,"127.0.0.1",function () {
    console.log("linsten")
});

 

GET:
前台代碼:
//簡單寫點樣式
<style>
        form{
            width: 200px;
            height: 200px;
            margin: 100px auto;
        }
        #content{
            width: 400px;
            height: 60px;
            border: 1px solid black;
            margin: auto;
            text-align: center;
            line-height: 60px;
            border-radius: 5px;
        }
        #submit{
            width: 175px;
            height: 30px;
            background-color: skyblue;
            margin: 20px 0;
            border: 1px solid white;
            border-radius: 5px;
        }
    </style>
//HTML
<body>
<div id="content">狀態顯示框</div>
<form action="http://127.0.0.1:8000/from" method="GET">//提交方式為GET
    <label for="login">用戶名:</label><br>
    <input id="login" type="text" name="user" placeholder="請輸入用戶名"><br>
    <label for="login">密碼:</label><br>
    <input id="pwd" type="password" name="pwd" placeholder="請輸入密碼"><br>
    <input id="submit" type="button" value="登錄" onclick="loadXMLDoc()"><br>
</form>
</body>
//JS
<script>
    function loadXMLDoc(){
        let xhr;
        let username = document.getElementsByName("user")[0];
        let userpwd = document.getElementsByName("pwd")[0];
        xhr = new XMLHttpRequest();
        let url = `http://127.0.0.1:8000/from?user=${username.value}&pwd=${userpwd.value}`
        //由於用ajax,get方式提交時url中不會顯示具體的url,但其提交方式仍然為get,本質還是不安全,可能在url網絡數據傳輸過程中被攔截。
        xhr.open("GET",url,true);
        xhr.send(null);
        xhr.onreadystatechange=function() {
            if (xhr.readyState==4 && xhr.status==200) {
                document.getElementById("content").innerHTML=xhr.responseText;
            }
            console.log(xhr.responseText)
        };
//        xhr.open("post","http://127.0.0.1:8000/from",true);
//        xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
//        xhr.send(`user=${username.value}&pwd=${userpwd.value}`);
//注釋掉的為POST方式請求代碼
    }
</script>
 
        

后台代碼:

const http = require("http");
const fs = require("fs");
const url = require("url");
let sever = http.createServer(function (req,res) {
    let pathname = url.parse(req.url).pathname;
    let query = url.parse(req.url,true).query;//字符串轉對象
    if(pathname === "/"){
        fs.readFile("./login.html",function (error,data) {
            if(!error){
                res.writeHead(200,{"content-type":"text/html"});
                res.end(data);
            }else {
                res.end("" + error);
            }
        })
    }else if(pathname === "/from"){
        console.log(query);//對象形式
        if(query.user === "tom" && query.pwd === "tom"){
            res.writeHead(200,{"content-type":"text/html;charset=utf-8"});
            res.write("登陸成功");
            res.end();
        }else{
            res.writeHead(200,{"content-type":"text/html;charset=utf-8"});
            res.write("登陸失敗");
            res.end();
        }
    }
});
sever.listen(8000,"127.0.0.1",function () {
    console.log("服務器已開啟")
});

總結:post和get本質上都是TCP鏈接,是HTTP中兩種發送請求的方法。,由於HTTP的規定和瀏覽器/服務器的限制,導致他們在應用過程中體現出一些不同。

 
        

區別一:最直觀的區別就是GET把參數包含在URL中,POST是通過request body 傳送參數,“request body”就是請求文件返回的內容。

 
        

區別二:get傳送的數據量較小,不能大於2KB。(取決於瀏覽器本身),post傳送的數據量較大,一般被默認為不受限制。可以上傳圖片、文件等非字符串格式數據。

 
        

區別三:因為GET參數通過URL傳遞,那么GET方式不是安全的,這里的安全指:比如賬號密碼登錄用GRT,別人可以通過URL看到你的信息,盡管通過ajaxURL地址欄不會顯示,但是仍然可以用firefox或者其他的軟件看到請求內容,實質上還是會通過URL網絡傳輸被截取到。

 
        

區別四:GET是“安全“的,這里的安全指的是不會改變服務器端的數據,只會接收請求,而POST則可以改變服務器上資源的請求。

今天的學習筆記就到這里,純個人手寫,如有發現錯誤,歡迎指出,非常感激! 


 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2026 CODEPRJ.COM