服务器发送请求(02):示例-查询天气

封装模块

weather.js

/*
    调用第三方:获取天气
 */

const http = require('http');


exports.queryWeather = (cityCode,callback)=>{
    let options = {
        protocol:'http:',
        hostname : 'www.weather.com.cn',
        port : 80,
        path:'/data/sk/' + cityCode + '.html',
        method:'get'
    }

    const req = http.request(options,(res)=>{
        let info = '';

        res.on('data',(chuck)=>{
            info += chuck;
        });

        res.on('end',()=>{
            info = JSON.parse(info);
            callback(info);
        });

    });

    req.end();
}

test.js

/*
测试weather.js
 */

const weather = require('./weather');

weather.queryWeather('101020100',(data)=>{
    console.log(data);
});

返回结果

{
  weatherinfo: {
    city: '上海',
    cityid: '101020100',
    temp: '23.5',
    WD: '东北风',
    WS: '小于3级',
    SD: '80%',
    AP: '1006.4hPa',
    njd: '2903',
    WSE: '<3',
    time: '17:00',
    sm: '1.1',
    isRadar: '1',
    Radar: 'JC_RADAR_AZ9210_JB'
  }
}

posted @ 2020-10-28 10:00  mrtransition  阅读(136)  评论(0)    收藏  举报