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

Time:2022-5-14

Some time ago, many disasters occurred 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!
Therefore, it was decided to build a complete real-time weather early warning project, mainly using node JS and the third-party free interface for aggregating data. The API management interface uses our developed apipost. There is no special advanced technology stack. It is mainly to attract jade by throwing bricks. I hope it will be helpful to you!
1、 Free weather forecast interface
There are many API interfaces for free access to weather on the Internet. I use the interface for aggregating data here, which is relatively stable for large factories.
Application address:https://www.juhe.cn/docs/api/…
After the application is successful, a request key will be generated in the personal center, which will be used when sending the interface.
10 minutes, using node JS creates a real-time early warning system for bad weather!

2、 Use the weather forecast interface and generate the program code

According to the instructions for the use of aggregated data, we can use the interface debugging tool to debug the interface. Here, we use the API post test.
10 minutes, using node JS creates a real-time early warning system for bad weather!
You can see that the JSON format after the request is successful is as follows:

{
    "Reason": "query succeeded",
    "result": {
        "City": "Zhengzhou",
        "realtime": {
            "temperature": "24",
            "humidity": "100",
            "Info": "light rain",
            "wid": "07",
            "Direct": "northeast wind",
            "Power2":,
            "aqi": "32"
        },
        "future": [
            {
                "date": "2021-07-23",
                "temperature": "23/28℃",
                "Weather": "light rain turns overcast",
                "wid": {
                    "day": "07",
                    "night": "02"
                },
                "Direct": "from east wind to north wind"
            },
            {
                "date": "2021-07-24",
                "temperature": "24/31℃",
                "Weather": "light rain turns cloudy",
                "wid": {
                    "day": "07",
                    "night": "01"
                },
                "Direct": "northeast wind to east wind"
            },
            {
                "date": "2021-07-25",
                "temperature": "23/31℃",
                "Weather": "cloudy",
                "wid": {
                    "day": "01",
                    "night": "01"
                },
                "Direct": "from east wind to southeast wind"
            },
            {
                "date": "2021-07-26",
                "temperature": "24/31℃",
                "Weather": "light rain",
                "wid": {
                    "day": "07",
                    "night": "07"
                },
                "Direct": "northeast wind"
            },
            {
                "date": "2021-07-27",
                "temperature": "23/31℃",
                "Weather": "light rain turns sunny",
                "wid": {
                    "day": "07",
                    "night": "00"
                },
                "Direct": "northeast wind to south wind"
            }
        ]
    },
    "error_code": 0
}

At this point, we have obtained the weather data for the next 7 days.

Step 3: use nodemailer to send mail in nodejs
Nodejs nodemailer is used to send mail, which is easy to use. You can use it by installing it with the following command:
npm install nodemailer
The following is a function I wrote to send e-mail, in which the e-mail account and authorization code can be obtained from the corresponding e-mail service provider.

/**
 *Nodejs send mail
 *
 * */
function sendEmail(text){
    let nodemailer = require('nodemailer');
 
    let transporter = nodemailer.createTransport({
        Service: "126", // mailbox
        Secure: true, // safe sending mode
        auth:{
            user:"be*** [email protected] ", // sender's mailbox
            Pass: "MLQ * * * PYU" // the authorization code is obtained from the mail service provider. The address of mailbox 126 is: https://help.mail.163.com/faq.do?m=list&categoryID=197
        }
    })
 
    let mailOptions = {
        from:"be*** [email protected] ", // the sender's mailbox is consistent with the sender's mailbox above
        to:" [email protected] ", // the recipient's mailbox, 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 ')

10 minutes, using node JS creates a real-time early warning system for bad weather!
Create a new weather JS, the content is the above code, through
node weather.js
You can test email sending.
10 minutes, using node JS creates a real-time early warning system for bad weather!
Send successfully, receive mail successfully.

Step 4: get the weather regularly in nodejs and send it to the specified mailbox
Click the generate nodejs (request) code in the upper right corner of API post to generate the program code for requesting aggregation weather interface in nodejs. We can realize the above requirements in combination with setinterval.
10 minutes, using node JS creates a real-time early warning system for bad weather!
All codes are as follows:

/**
 *Nodejs send mail
 * 
 * */
function sendEmail(text){
    let nodemailer = require('nodemailer');

    let transporter = nodemailer.createTransport({
        Service: "126", // mailbox
        Secure: true, // safe sending mode
        auth:{
            user:"be*** [email protected] ", // sender's mailbox
            Pass: "MLQ * * * PYU" // the authorization code is obtained from the mail service provider. The address of mailbox 126 is: https://help.mail.163.com/faq.do?m=list&categoryID=197
        }
    })

    let mailOptions = {
        from:"be*** [email protected] ", // the sender's mailbox is consistent with the sender's mailbox above
        to:" [email protected] ", // the recipient's mailbox, 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 ('Future weather in Zhengzhou '+ JSON. Result. Future [0]. Weather)
        }
    }

    request(options, callback);

}, 300000);

So far, all the systems have been built. We just need to find a small server to execute
node weather.js
You can send the weather information to the designated mailbox every 5 minutes. Of course, you can also send it as needed.

matters needing attention:
Because the Chinese code may have problems in the request, it is best to encode the city name (right click).
10 minutes, using node JS creates a real-time early warning system for bad weather!
Welcome to like, comment and exchange, and learn about the latest news of apipost~