静态页面显示效果:
服务器获取的源信息:
实现思路:NodeJS搭建服务器,从天气网站获取天气信息,前端通过Ajax接收数据并显示。
重点:NodeJS获取天气信息,获取信息在前后端的传输。
NodeJS获取天气信息并传递给前端(后台代码)
首先通过http从网站上获取天气信息,此处的url为天气网站地址(http://www.weather.com.cn/data/cityinfo/101270401.html);再利用express模块的app.post接收前端的数据请求(刷新天气信息),并返回对应的数据(具体天气信息)。app.post设置一个url接口(这里为/postTest)与前端Ajax中的url对应,方便数据的传输与处理。
server.js:
var http = require('http');
const express = require('express');
const app = express();
// 解析post请求带过来的参数
const bodyParser = require('body-parser');
app.use(express.static(__dirname));//使用绝对路径
var jsonData = '';//存储天气信息
var url_ = "http://www.weather.com.cn/data/cityinfo/101270401.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.post("/postTest", 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
});
});
Ajax获取后台天气数据并显示(前端js代码)
url为与后台接口对应的/postTest。
index.js:
//页面加载时的天气预报
$.ajax({
type: "post",
url: "/postTest",
success: function(res) {
$('#city em').text(res['city']);
$('#weather').text(res['weather']);
$('#img1').attr('src', 'http://www.weather.com.cn/m/i/weatherpic/29x20/'+res['img1']);
$('#img2').attr('src', 'http://www.weather.com.cn/m/i/weatherpic/29x20/'+res['img2']);
$('#temp em').text(res['temp2']+'/'+res['temp1']);
}
});
//点击城市名后刷新天气预报
$('#city').on('click', function(){
$.ajax({
type: "post",
url: "/postTest",
success: function(res) {
$('#city em').text(res['city']);
$('#weather').text(res['weather']);
$('#img1').attr('src', 'http://www.weather.com.cn/m/i/weatherpic/29x20/'+res['img1']);
$('#img2').attr('src', 'http://www.weather.com.cn/m/i/weatherpic/29x20/'+res['img2']);
$('#temp em').text(res['temp2']+'/'+res['temp1']);
}
});
});
静态html页面与css样式代码
index.html:
<!-- 天气预报 -->
<div id="weatherInfo">
<span id="city"><em></em></span>
<span id="weather"></span>
<img id="img1" src=""><img id="img2" src="">
<span id="temp"><em></em></span>
</div>
index.css:
#weatherInfo span{
float:left;
font-size:17px;
line-height:30px;
height:30px;
text-align:right;
position:relative;
}
#weatherInfo em{
line-height:30px;
margin:0 10px;
color:#043567;
font-size:16px;
}
程序运行过程
1.根目录下启动server.js。在server.js所在文件目录下按住shift按钮并右击鼠标,选择“在此处打开powershell窗口”。输入node.server.js;2.浏览器输入127.0.0.1:8888/index.html