current position:Home>10 minutes, using node JS creates a real-time early warning system for bad weather!

10 minutes, using node JS creates a real-time early warning system for bad weather!

2022-01-26 22:04:50 apipost

Some time ago , There have been many disasters in China , Zhengzhou high tech Zone, where we were located at that time, experienced water and power cuts , It's frightening to think of it !
So I decided to build a complete real-time weather warning project , Mainly used Node.JS And a third-party free interface for aggregating data ,api The management interface is developed by us apipost, There is no particularly advanced technology stack , It's mainly about casting a brick to attract jade , I hope that's helpful !
One 、 Free weather forecast interface
There are many free weather on the Internet API Interface , What I use here is the interface for aggregating data , The relative stability of large factories .
To apply for the address :https://www.juhe.cn/docs/api/...
After successful application , A request will be generated in the personal Center key, When sending the interface , Want to use .

Two 、 Use the weather forecast interface and generate program code

According to the usage instructions of aggregated data , We can use the interface debugging tool to debug the interface , We use ApiPost test .

You can see... After the request is successful json The format is as follows :

{
    "reason": " The query is successful !",
    "result": {
        "city": " zhengzhou ",
        "realtime": {
            "temperature": "24",
            "humidity": "100",
            "info": " Light rain ",
            "wid": "07",
            "direct": " northeasterly wind ",
            "power": "2 level ",
            "aqi": "32"
        },
        "future": [
            {
                "date": "2021-07-23",
                "temperature": "23/28℃",
                "weather": " Light rain turns to overcast ",
                "wid": {
                    "day": "07",
                    "night": "02"
                },
                "direct": " East wind turns north "
            },
            {
                "date": "2021-07-24",
                "temperature": "24/31℃",
                "weather": " Light rain turns cloudy ",
                "wid": {
                    "day": "07",
                    "night": "01"
                },
                "direct": " The northeast wind turns to the east wind "
            },
            {
                "date": "2021-07-25",
                "temperature": "23/31℃",
                "weather": " cloudy ",
                "wid": {
                    "day": "01",
                    "night": "01"
                },
                "direct": " East wind to southeast wind "
            },
            {
                "date": "2021-07-26",
                "temperature": "24/31℃",
                "weather": " Light rain ",
                "wid": {
                    "day": "07",
                    "night": "07"
                },
                "direct": " northeasterly wind "
            },
            {
                "date": "2021-07-27",
                "temperature": "23/31℃",
                "weather": " Light rain turns sunny ",
                "wid": {
                    "day": "07",
                    "night": "00"
                },
                "direct": " Northeast to South "
            }
        ]
    },
    "error_code": 0
}

To this step , We've got the future 7 Days of weather data .

The third step : utilize nodemailer stay NodeJS Middle mail
nodeJS Of nodemailer For sending mail , useful . Install with the following command to use :
npm install nodemailer
The following is a function I wrote to send mail , The mailbox account and authorization code can be obtained from the corresponding mailbox service provider .

/**
 * nodeJS  Send E-mail 
 *
 * */
function sendEmail(text){
    let nodemailer = require('nodemailer');
 
    let transporter = nodemailer.createTransport({
        service:"126",  //   mailbox 
        secure:true,    //   Secure send mode 
        auth:{
            user:"be***[email protected]", //   Sender email 
            pass:"MLQ***PYU"//   Authorization code , Get... From a mail service provider ,126 The email address is :https://help.mail.163.com/faq.do?m=list&categoryID=197
        }
    })
 
    let mailOptions = {
        from:"be***[email protected]", //  Sender email , Just keep consistent with the sender's mailbox above 
        to:"[email protected]", //  Recipient email , That is, the mailbox that receives the weather forecast in real time 
        subject:" Real time weather monitoring system ", //  Email subject ( title )
        text:text //  Email solicitation 
    }
 
    transporter.sendMail(mailOptions,(err,data) => {
        if(err){
            console.log(err);
            res.json({status:400,msg:"send fail....."})
        }else{
            console.log(data);
            res.json({status:200,msg:" Mail sent successfully ....."})
        }
    })
}

//  Test email 
sendEmail(' It's raining ')


Create a new one weather.js , The content is the above code , adopt
node weather.js
You can test email sending .

Send successfully , Email received successfully .

Step four : stay nodeJS Get the weather regularly and send it to the specified mailbox
Click on ApiPost The generation in the upper right corner NodeJS(Request) Code , Can be generated in nodejs Program code for requesting aggregate weather interface in , We combine setInterval The above requirements can be realized .

All codes are as follows :

/**
 * nodeJS  Send E-mail 
 * 
 * */
function sendEmail(text){
    let nodemailer = require('nodemailer');

    let transporter = nodemailer.createTransport({
        service:"126",  //   mailbox 
        secure:true,    //   Secure send mode 
        auth:{
            user:"be***[email protected]", //   Sender email 
            pass:"MLQ***PYU"//   Authorization code , Get... From a mail service provider ,126 The email address is :https://help.mail.163.com/faq.do?m=list&categoryID=197
        }
    })

    let mailOptions = {
        from:"be***[email protected]", //  Sender email , Just keep consistent with the sender's mailbox above 
        to:"[email protected]", //  Recipient email , That is, the mailbox that receives the weather forecast in real time 
        subject:" Real time weather monitoring system ", //  Email subject ( title )
        text:text //  Email solicitation 
    }
    transporter.sendMail(mailOptions,(err,data) => {
        if(err){
            console.log(err);
            res.json({status:400,msg:"send fail....."})
        }else{
            console.log(data);
            res.json({status:200,msg:" Mail sent successfully ....."})
        }
    })
}

setInterval(function(){
    var request = require('request');

    var headers = {
        'User-Agent': 'Apipost client Runtime/+https://www.apipost.cn/'
    };

    var options = {
        url: 'http://apis.juhe.cn/simpleWeather/query?city=%E9%83%91%E5%B7%9E&key=8763efe2a90b025c03e03fef95621cbc',
        headers: headers
    };

    function callback(error, response, body) {
        let json = JSON.parse(body);
        console.log(json.result)
        if (!error && response.statusCode == 200) {
            sendEmail(' The future weather in Zhengzhou ' + json.result.future[0].weather)
        }
    }

    request(options, callback);

}, 300000);

thus , All the systems have been built . We just need to find a small server to execute
node weather.js
Command every 5 Send the weather conditions to the designated mailbox once a minute , Of course , You can also send... As needed .

matters needing attention :
Because the Chinese code may be in request So the city name is the best encode once ( Right click ).

Welcome to comment and exchange , understand ApiPost The latest news ~

copyright notice
author[apipost],Please bring the original link to reprint, thank you.
https://en.cdmana.com/2022/01/202201262204486678.html