最近一段時間在學習前端向服務器發送數據和請求數據,下面總結了一下向服務器發送請求用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 != '[email protected]' || 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>
服務器:
首先也需要安裝所用到的模塊,然后請求模塊使用;
var express = require('expres');var app = express();app.use(express.static('wwwroot'));app.get('/comment',function(request,response){ response.send('已經接受到用get方法發來的評價');})app.listen('3000',function(){ console.log('服務器啟動中');})
(2)xhr之post方法:
前端:
<button click = "post()">post方法</button><script>function post(){ var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function() { if(xhr.readyState == 4) { console.log('接收到服務器返回的信息' + xhr.responseText); } } xhr.open('post','/comment'); // post方法請求的參數不寫在open里面,寫在send里面,而且需要設置請求頭; xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded'); xhr.send('custom=小明&score=3&comment=商品還好,快遞也及時,但是就想給3分');}</script>
服務器:
需要引入post方法所用到的模塊(body-parser模塊)以及對url編碼;
var express = require('express');var bodyParser = require('body-parser');var app = express();app.use(express.static('wwwroot'));app.use(bodyParser.urlencoded({extended:false}));app.post('/comment',function(request,response){ response.send('已經接收到用post方法發送來的評價');})app.listen('3000',function(){ console.log('服務器啟動中');})
(3)xhr之formdata方法:
前端:
<button click = "formdata()">formdata方法</button><script>function formdata(){ var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function() { if(xhr.readyState == 4) { console.log('formdata方法返回的數據是:' + xhr.responseText); } } xhr.open('post','/comment'); var form = new FormData(); form.append('custom','小明'); form.append('score','5'); form.append('comment','看你那么辛苦,給你5分好了'); xhr.send(form);}</script>
服務器:
var express = require('express');var bodyParser = require('body-parser');var multer = require('multer'); // 使用form表單所需要用到的一個模塊var formData = multer();var app = express();app.use(express.static('wwwroot'));app.use(bodyParser.urlencoded({extended:false}));// 如果使用formdata提交的數據,必須在參數中使用array(),array()會先解析請求體當中的數據,再傳輸數據app.post('/comment',formData.array(),function(request,response) { response.send('已經接收到用post方法發送來的評價');})app.listen('3000',function(){ console.log('服務器啟動中');})
3.ajax請求:
一般情況下都不需要使用ajax請求 使用ajax請求可以獲取錯誤信息以及其它的一些指令,使用ajax需要引用jquery
(1)ajax之get:
前端:
<button id = "get">ajax-get</button><script>$('#get').click(function(){ $.get('/login',{name:'小明',password:'123456'},function(data,status,xhr) { console.log('服務器返回的信息是' + data); })// $.get() 發起一個get請求,參數1:請求的接口;參數2:傳遞給服務器的數據對象;參數3:回調函數(參數1:服務器返回的數據;參數2:狀態;參數3:xhr對象”);})</script>
服務器:
var express = require('express');var app = express();app.use(express.static('wwwroot'));app.get('/login',function(){ if(request.query.name == '小明' && request.query.password == '123456') { response.send('登錄成功'); } else { response.send('登錄失敗'); }})app.listen('8080',function(){ console.log('服務器啟動中');})
(2)ajax之post:
前端:
<button id = 'post'>ajax-post</button><script> $('#post').click(function(){ $.post('/login',{name:'小明',password:'666'},function(data,status,xhr) { console.log('服務器返回的數據:' + data) })})</script>
服務器:
var express = require('express'); var bodyParser = require('body-parser'); var app = express(); app.use(express.static('wwwroot')); app.use(bodyParser.urlencoded({extended:false}));app.listen('8080',function(){ console.log('服務器啟動中');})app.post('/login',function(request,response){ if(request.body.name == '小明' && request.body.password == 666) { response.send('登錄成功'); } else { response.send('登錄失敗'); }})
(2)ajax之ajax:
前端:
<button id ="ajax">ajax請求</button><script> $('#id').click(function(){// $.ajax() 發起ajax請求; $.ajax({ url :'/login', // 請求的接口地址 type:'post', // 請求的方式,默認為get請求 data:{name:'小明',password:'123'}, // 發送到服務器的數據 timeout:10000, // 超時 (10s) cache:true, // 緩存 默認為true async:true, // 是否異步 // 同步任務(sync) :當上一個任務沒有完成的時候,下一個任務無法開啟,有可能會卡死主線程;//異步任務(Async):當上一個任務沒有完成的時候,下一個任務仍然會被執行,用戶體驗性好; success:function(data,status,xhr) { console.log('服務器返回的數據是:' + data); console.log('返回的信息是:' + xhr.getAllResponseHeaders()); } error:function(xhr,status,error) { console.debug('錯誤信息:' + error); } complete:function(xhr,status) { console.log('全部流程結束'); }}) })</script>
服務器里面可以使用上面ajax的get和post方法的代碼,ajax請求的方式通過type設置為get方式還是post方式。
以上這篇nodejs之get/post請求的幾種方式小結就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持武林網。
新聞熱點
疑難解答