Ajax---向服务器端传递JSON格式的请求参数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','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        load=function(){
21            console.sponseText)//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
发送ajax请求的步骤
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')