1.1 $.post() 发送请求
NodeJS的post请求,post请求是通过请求体获得参数的
index.html
<h1>向nodejs服务器端提供的接口地址,发送一个请求,并且传递数据</h1>
<div id="info">
<div>
<label for="">姓名:</label>
<input type="text" name="" id="uname">
<div>
<label for="">年龄:</label>
<input type="text" name="" id="age">
</div>
<div>
<label for="">性别:</label>
<input type="radio" name="sex" id="" value="男">男
<input type="radio" name="sex" id="" value="女">女
</div>
<div>
<button id="btn">点击它,发送post请求</button>
</div>
</div>
</div>
<script src="./jquery-3.5.1/jquery-3.5.1.min.js"></script>
<script>
$(function(){
$('#btn').click(function(){
//读取表单
var uname=$('#uname').val();
var age=$('#age').val();
var sex=$("input[name='sex']:checked").val()
console.log(uname);
console.log(age);
console.log(sex);
//发送请求
var apiUrl='http://127.0.0.1:5500/addstu'
$.post(apiUrl,{
uname,
age,
sex
},function(data){
console.log('服务器端响应返回的数据是:'+data);
console.log(data);
})
})
})
</script>
index.js
var http = require('http');
const express = require('express');
const app = express();
app.all('*', function (req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header('Access-Control-Allow-Headers', "*");
res.header("Access-Control-Allow-Methods", "*");
res.header("Access-Control-Allow-Credentials", true);
next();
});
// 解析post请求带过来的参数
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({extended:false}));
app.use(express.static(__dirname));//使用绝对路径
var jsonData = '';//存储天气信息
// var url_ = "http://www.weather.com.cn/data/cityinfo/101220101.html";//合肥的天气预报信息
var url_='http://www.weather.com.cn/data/cityinfo/101220601.html'//安庆的天气预报
http.get(url_, function (res) {//通过上面传过来的url来获取该天气信息的数据
res.on("data", function (data) {
jsonData += data.toString('utf8');//保存天气信息的数据
})
res.on('end', function(){
jsonData = JSON.parse(jsonData);
})
});
app.get("/list", function(req, res) {
// 返回josn数据
res.send(jsonData);
// res.send('hi nodejs')
});
app.post('/addstu',function(req,res){
// console.log(req);
console.log(req.body);
res.send(req.body)
})
app.post("/wlist", function(req, res) {
// 返回josn数据
// return res.json({//只返回需要的数据
// city:jsonData.weatherinfo.city,//城市名
// weather: jsonData.weatherinfo.weather,//天气
// temp1:jsonData.weatherinfo.temp1,//最低温
// temp2:jsonData.weatherinfo.temp2,//最高温
// img1:jsonData.weatherinfo.img1,//天气图片1
// img2:jsonData.weatherinfo.img2//天气图片2
// });
return res.json(jsonData);
});
const port = 5500;
// 设置端口
app.listen(port,'127.0.0.1',()=>{
console.log(`服务器运行在localhost:${port}`);
})
预览:
终端预览:
在postman中发送数据,需要在body里面添加数据
预览:
终端预览: