Ajax---向服务器端发送POST数据


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

运行结果:

 

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM