POST請求方式1:application/x-www-form-urlencoded
name=zhangsan&age=20
xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded')
xhr.send('name-zhangsan&age=20');
請求報文
在HTTP請求和響應的過程中傳遞的數據塊就叫報文,包括要傳送的數據和一些附加信息,這些數據和信息要遵守規定好的格式。
安裝body-parser,在項目根目錄下輸入:npm install --save body-parser
body-parse:https://blog.csdn.net/web_youth/article/details/80053187
.html
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="utf-8"> 5 <title>Document</title> 6 </head> 7 <body> 8 <p> 9 <input type="text" id="username" > 10 </p> 11 <p> 12 <input type="text" id="age"> 13 </p> 14 <p> 15 <input type="button" value="提交" id='btn'> 16 </p> 17 <script type="text/javascript"> 18 //獲取按鈕元素 19 var btn=document.getElementById('btn'); 20 //獲取姓名文本框 21 var username=document.getElementById('username'); 22 //獲取年齡文本框 23 var age=document.getElementById('age'); 24 //為按鈕添加點擊事件 25 btn.onclick=function(){ 26 //創建ajax對象 27 var xhr=new XMLHttpRequest(); 28 //獲取用戶在文本框中輸入的值 29 var nameValue=username.value; 30 var ageValue=age.value; 31 32 //拼接請求參數 33 var params='username='+nameValue+'&age='+ageValue; 34 35 //配置Ajax對象 36 xhr.open('post','http://localhost:3000/post'); 37 38 //設置請求參數格式的類型(post請求必須要設置) 39 xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded'); 40 //發送請求 41 xhr.send(params); 42 //獲取服務器端響應的數據 43 xhr.onload=function(){ 44 console.log(xhr.responseText) 45 } 46 } 47 </script> 48 </body> 49 </html>
app.js
//引入express框架 const express=require('express') //引入路徑處理模塊 const path=require('path') const bodyParser=require('body-parser'); //創建web服務器 const app=express(); //使用bodyParser.urlencoded(),使node后台支持了第一種請求體. app.use(bodyParser.urlencoded());//extended: true //使用bodyParser.json(),使node后台支持了第二種請求體. app.use(bodyParser.json()); //靜態資源訪問服務器功能 app.use(express.static(path.join(__dirname,'public'))) //對應04傳遞post請求參數.html app.post('/post',(req,res)=>{ res.send(req.body); }) //監聽端口 app.listen(3000); //控制台提示輸出 console.log('服務器啟動成功4')
運行結果: