国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 語言 > JavaScript > 正文

nodejs之get/post請求的幾種方式小結

2024-05-06 15:13:52
字體:
來源:轉載
供稿:網友

最近一段時間在學習前端向服務器發送數據和請求數據,下面總結了一下向服務器發送請求用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>            
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表

圖片精選

主站蜘蛛池模板: 临安市| 保德县| 电白县| 措美县| 来凤县| 西峡县| 洪湖市| 南投市| 旬邑县| 南靖县| 福州市| 肃宁县| 巢湖市| 临泽县| 北海市| 措美县| 峨山| 十堰市| 色达县| 河北省| 团风县| 都兰县| 浙江省| 海伦市| 阳谷县| 栖霞市| 永州市| 漾濞| 灵台县| 鄂托克旗| 新竹县| 龙井市| 蓬莱市| 朔州市| 镇沅| 牡丹江市| 任丘市| 蕉岭县| 濉溪县| 金平| 尼木县|