technicist

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\')

 

分类:

技术点:

相关文章: