当前位置:网站首页>Node+js build time server
Node+js build time server
2022-07-25 08:01:00 【Words and deeds yyds】
List of articles

️ Author's brief introduction : Hello, everyone, I'm talking and doing yyds
Personal home page : speeches are not in accordance with action yyds Of CSDN Blog
Series column :【 Front end training 】
Time server
Time server
1. Train of thought
1. Source of ideas
This is from my software teacher Final course design
What he wants is through his knowledge reserve , To design a
Display and transmission of front and rear data
1.2 Thinking premise requirements
1. Build a front page , Simple and easy to understand
2. Set up server , It is used to send the required data to the front end
3. Click data display , color changing , Double click to switch some background colors
1.3 technical requirement
1. be familiar with node, Have a good command of fs Use
2. Know how to use express Build a background server ,
Learn how to send data to the front station
3. Be aware of the overall situation , Will need to change the color
For setting var() To set the color
4. Be familiar with the method of array , Learn how to process data through array method
5. understand echarts Use
6. be familiar with ajax Use
2. Realization
2.1 Implementation preparation
Here I pass a software , To achieve ready design
To realize the plan of the project . Software is Pixos
Here I hope you can design a project before
We must make some preparations , Design a sketch

2.2 Set up the front page
About this front page , I believe your strength , It shouldn't be difficult
The built front page is as follows :

2.3 Build a background server
2.3.1 Set up the backstage
Download... In the project express npm i express --save
// Set up a local server
// The port number is 8000
const express=require('express')
const fs=require('fs')
const app=express()
app.listen(8000,()=>{
console.log(" Open successfully ")
})
2.3.2 Background processing of data to be sent
There are two kinds of data that need to be sent in the background
1. Real time date , And the current time
2. Real time seven day weather information
2.3.2.1 Real time
By instantiating Date() Functions can be implemented .
Then get the time information through the corresponding function .
And then the data is JSON turn , Processing data format when sending
Here we will set an interface , Used for front-end data acquisition .
/timeDate Interface
app.get('/timeDate',(req,res)=>{
// Used to deal with cross domain problems
res.setHeader('Access-Control-Allow-Origin', '*');
// Response head
res.setHeader('Access-Control-Allow-Headers', '*');
// Instantiate built-in Date() library
var time=new Date()
// Get years
const year=time.getFullYear()
const mouth=time.getMonth()+1
const day=time.getDate()
const hour=time.getHours()
const min=time.getMinutes()
const second=time.getSeconds()
// Put the data json turn , To transmit data
const TimeDate={
year,mouth,day,hour, min,second}
// Send data to client
res.send(JSON.stringify(TimeDate))
})
2.3.2.2 Seven day weather information
This seven day information is obtained through online data .
On the official website Weather official website You can get real-time information every day .
You can also get it through the data interface I created Data interface
Considering the time of the request , I store the data in data.json in
Used to improve the time of data request and sending .
What is achieved is through fs Module reads data , Then get the data ,
Create an interface , Send data to the front end

Then there is the background code :
fs.readFile('./data.json',(err,data)=>{
if(err) return console.log('err')
let result=JSON.parse(data)
app.get('/weatherDate',(req,res)=>{
res.setHeader('Access-Control-Allow-Origin', '*');
// Response head
res.setHeader('Access-Control-Allow-Headers', '*');
res.send(result)
})
})
2.4 The data obtained by front-end processing
2.4.1 Time data
What we need to do is to get the time data .
Show it to the corresponding position .
1. Time clock 2. Time to show
Get the corresponding DOM structure , Then set the js And css style
The process is :
Bind click event ==》 adopt ajax Get interface data
==》 Get the corresponding DOM Interface =+=》 insert data , Set up css style
/* Render the clock */
// When you get it , branch , Of a second DOM structure
const hours=document.querySelector(".hour")
const mins=document.querySelector('.min')
const seconds=document.querySelector('.seconds')
// Get six empty places DOM structure
const item1=document.querySelector('.item1')
const item2=document.querySelector('.item2')
const item3=document.querySelector('.item3')
const item4=document.querySelector('.item4')
const item5=document.querySelector('.item5')
const item6=document.querySelector('.item6')
// Bind click event
const bottom=document.getElementById('bottom')
bottom.addEventListener('click',timeshow)
function timeshow(){
let xhr=new XMLHttpRequest()
xhr.open("GET",'http://localhost:8000/timeDate')
xhr.send()
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status >= 200 && xhr.status < 300) {
// Structure the requested data
let result =JSON.parse(xhr.response);
// When you get it
let hour = result.hour
const hourDeg = (hour / 12) * 360 + 90
hours.style.transform = `rotate(${
hourDeg}deg)`;
// Get points
let min = result.min
const minDeg = (min / 60) * 360 + 90
mins.style.transform = `rotate(${
minDeg}deg)`
// Get seconds
let second = result.second
const secondDeg = (second / 60) * 360 + 90
seconds.style.transform = `rotate(${
secondDeg}deg)`
// Insert the data into the specified location
item1.innerHTML =result.year
item2.innerHTML =result.mouth
item3.innerHTML = result.day
item4.innerHTML =result.hour
item5.innerHTML = result.min
item6.innerHTML = result.second
} else {
console.log("err")
}
}
}
}

2.4.2 Weather information
I just got the weather information data part .
The data needed is .
1. Seven days , And their corresponding highest , Minimum temperature
2. Seven days' temperature , And the corresponding warm prompt information .
I use histogram to show the height of time .
Temperature and prompt are represented by pie chart
Set up echarts Chart time , The most important thing is data data
, Other auxiliary information can be set according to the prompts of the pipe network
2.4.2.1 Time data processing
Get interface data , Get the corresponding value
let xhr=new XMLHttpRequest()
xhr.open("GET",'http://localhost:8000/timeDate')
xhr.send()
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status >= 200 && xhr.status < 300) {
var result=JSON.parse(xhr.response)
var data=result.data
console.log(data)
// Because the data obtained is an array ,
// and option Of data The format of the data is json Format .
// So we need to process the data
const maxMINArr=data.map((item)=>{
return {
product:item.date, Minimum temperature :item.tem1, maximum temperature :item.tem2}
})
}
//echarts Medium option Property settings for
dataset: {
dimensions: ['product', ' maximum temperature ', ' Minimum temperature '],
source:maxMINArr
},

2.4.2.2 Temperature and tips
It should be noted that the data obtained is
Array , and echarts Of option Set data
What is needed is json The form of class , therefore
The data needs to be json turn
let xhr=new XMLHttpRequest()
xhr.open("GET",'http://localhost:8000/timeDate')
xhr.send()
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status >= 200 && xhr.status < 300) {
var result=JSON.parse(xhr.response)
const dataArr=data.map(item=>{
return {
value:item.tem,name:item.date,level:item.air_level,tips:item.index[3]}
})
//echarts Medium option Property settings for
tooltip:{
show:true,
// Prompt information json Standardized data
formatter: function(arg){
return arg.data.name+' : '+arg.data.value+'c'+' : '+arg.data.level+' : '+arg.data.tips.desc
}
},
series: [
{
name: 'Access From',
type: 'pie',
radius: '50%',
data:dataArr,
emphasis: {
itemStyle: {
shadowBlur: 10,
shadowOffsetX: 0,
shadowColor: 'rgba(0, 0, 0, 0.5)'
}
}
}
]
}

2.5 Effect display
Time server
3. summary
1. understand node Of fs How the module reads data
2. understand express How to build a server , Set the data interface
3. Learn to echarts Settings and use of
4. Learn how to change the global color
5. understand ajax How to deal with background data
边栏推荐
- How does MTK change the boot logo?
- Gather the wisdom of developers and consolidate the foundation of the database industry
- Can Flink's current capabilities support the synchronization of a table from source (MySQL) to sink (MySQL) to separate databases and tables
- If Debian infringes the rust trademark, will it be exempted by compromising and renaming?
- Eval and assert one sentence Trojan horse analysis
- Problems easily ignored by POM
- mysql 如何获取两个集合的交集/差集/并集
- [audio and video] picture YUV data format
- 【FFmpeg】mp4转yuv
- 轮询、中断、DMA和通道
猜你喜欢

475-82(230、43、78、79、213、198、1143)

Eval and assert one sentence Trojan horse analysis

App power consumption test

Today in history: Intel was founded; The first photo was posted on the world wide web; EBay spins off PayPal

轮询、中断、DMA和通道

Practical operation: elegant downtime under large-scale micro service architecture
![[wechat applet] global style, local style, global configuration](/img/8e/c6241ab0f28e3f468dbfa923b91d20.png)
[wechat applet] global style, local style, global configuration

Niuke dynamic planning training

【音视频】图片YUV数据格式

Introduction and installation of mongodb
随机推荐
Nano data, football data, football match scores, sports data API, Qatar world cup
用一个栈实现另一个栈的排序
Learn no when playing 8 | the enterprise saves hundreds of thousands in an instant, just because it uses it
【Unity入门计划】基本概念-触发器 Trigger
P1049 [NOIP2001 普及组 T4] 装箱问题
RK3399开发板I2C4挂载EEPROM实例
7.24模拟赛总结
redis客户端工具redis-insight推荐
【ES6】函数的参数、Symbol数据类型、迭代器与生成器
CAS操作
【音视频】图片YUV数据格式
New version 8.6 SEO quick release system (can be built at source level)
P1049 [noip2001 popularization group t4] packing problem
Niuke dynamic planning training
toolbar的使用
查看电脑重启次数、原因
Introduction to machine learning (I): understanding maximum likelihood estimation in supervised learning
475-82(230、43、78、79、213、198、1143)
轮询、中断、DMA和通道
Leetcode (Sword finger offer) - 04. search in two-dimensional array