最近一段時間在學習前端向服務器發送數據和請求數據,下面總結了一下向服務器發送請求用get和post的幾種不同請求方式:
1.用form表單的方法:
(1)get方法
前端代碼:
<form action = "/login" method = "GET"> <label for = "username">賬號:</label> <input type = "text" name ="username" placeholder = "請輸入賬號" required> <br> <label for = "password">密碼:</label> <input type = "password" name = "password" placeholder = "請輸入密碼" required> <br> <input type = "submit" value = "登陸"></form>
服務器代碼:
用get方法首先要配置json文件,在command中輸入命令npm-init ,然后要安裝所需要的express模塊,還需要在文件夾里面創建一個放置靜態資源的文件夾(wwwroot),然后代碼如下:
var express = require('express'); // 引入模塊var web = express(); // 使用模塊創建一個web應用web.use(express.static('wwwroot')); // 調用use方法 使用static方法web.get('/login',function(request,response) { 使用get方法 參數1 接口 參數2 回調函數 (參數1 向服務器發送的請求 參數2 服務器返回的數據) var name = request.query.username; // 獲取前端發送過來的賬號 var psw = request.query.password; // 獲取前端發送過來的密碼 response.status('200').send('輸入的內容是' + name + '<br>' + psw);})web.listen('8080',function() // 監聽8080端口 啟動服務器{ console.log('服務器啟動中');})(2)post方法
前端:用post方法需要將form里面的 method = GET 改成 mthod = POST,表示使用post方法;
服務器:除get方法的要求外,還需要引入 body-parser模塊,以及對url進行編碼;
var express = require('express');var bodyParser = require('body-parser');var web = express();web.use(express.static('wwwroot'));// url 統一資源調配符 encoded 編碼 web.use(bodyParser.urlencoded({extended:false}));web.post('/login',function(request,response){ var name = request.body.username; var psw = request.body.password; if(name != '599115316@qq.com' || psw != '123456') { response.send('<span style = "color:blue">登錄失敗</span>') } else { response.send('<span style = "color:red">登陸成功</span>') }})web.listen('8080',function(){ console.log('服務器啟動中');})2.xhr(XML HTTP Request方法 有三種請求方式 get/post/formdata)
XHR是ajax的核心,使用XHR可以向服務器發送數據 也可以解析服務器返回的數據;
(1)xhr之get方法:
前端:
<button click = "get()">get方法</button><script>function(){ var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function() { if(xhr.readyState == 4) {console.log(xhr.responseText)} // 服務器接收到數據后返回的數據 } xhr.open('/get','/comment?custom=小明&score=2&comment=商品質量一般,2分是給快遞小哥的'); xhr.send();// xhr.open(); 里面有三個參數 ,參數1:設置xhr請求服務器的時候,請求的方式;參數2:設置請求的路徑和參數;(?是路徑和參數的分割線);參數3:設置同步請求還是異步請求,不寫的話默認為異步請求;}</script>
新聞熱點
疑難解答
圖片精選