POST請求方式2:application/JSON
{name:'zhangsan',age:'20'}
在請求頭中指定Content-Type屬性的值是application/json,告訴服務器當前請求參數的格式是json.
JSON.stringify()//將json對象轉換為json字符串
.html文件
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="utf-8"> 5 <title>Document</title> 6 </head> 7 <body> 8 <script type="text/javascript"> 9 //創建Ajax對象 10 var xhr=new XMLHttpRequest(); 11 //2、告訴Ajax對象要向哪發送請求,以什么方式發送請求(請求方式,請求地址) 12 xhr.open('post','http://localhost:3000/json'); 13 14 //通過請求頭告訴服務器端客戶端向服務器端傳遞的請求參數的格式是什么 15 xhr.setRequestHeader('Content-Type','application/json'); 16 //JSON.stringify() 將json對象轉換為json字符串 17 //3、發送請求 18 xhr.send(JSON.stringify({name:'lisi',age:22})); 19 //4、獲取服務器端響應到客戶端的數據 20 xhr.onload=function(){ 21 console.log(xhr.responseText)//Hello Ajax 22 23 } 24 </script> 25 </body> 26 </html>
f12打開瀏覽器調試界面
app.js
1 //引入express框架 2 const express=require('express') 3 4 //引入路徑處理模塊 5 const path=require('path') 6 const bodyParser=require('body-parser'); 7 8 //創建web服務器 9 const app=express(); 10 11 //使用bodyParser.urlencoded(),使node后台支持了第一種請求體. 12 app.use(bodyParser.urlencoded());//extended: true 13 //使用bodyParser.json(),使node后台支持了第二種請求體. 14 app.use(bodyParser.json()); 15 16 //靜態資源訪問服務器功能 17 app.use(express.static(path.join(__dirname,'public'))) 18 19 //05向服務器端傳遞JSON格式的請求參數.html 20 app.post('/json',(req,res)=>{ 21 res.send(req.body); 22 }) 23 24 25 //監聽端口 26 app.listen(3000); 27 28 //控制台提示輸出 29 console.log('服務器啟動成功5')