如何与外部源交互

本文介绍了一个使用Node.js实现的简单天气查询服务。该服务通过HTTP请求从OpenWeatherMap获取天气信息,并将其显示在一个简单的网页上。用户可以提交城市名称来获取对应的天气情况。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、原理

  1. 先利用http.createServer()创建本站服务器,解析每次收到的请求参数,获得外部源(其他网站)需要的参数;
  2. 使用http.request()创建客户端对象,并根据传入的参数构建URL,获得外部源的响应信息,解析出所需信息;  //充当一个虚拟浏览器
  3. 将解析到的信息在本站输出。

二、实例

  1、代码如下:

/**
 * Created by Soul on 2016/7/4.
 */
var http=require("http");
var url=require("url");
var qString=require("querystring");

function sendResponse(weatherData,res){
    var page='<html><head><meta charset="utf-8"><meta http-equiv="X-UA-Compatible" co' +
        'ntent="IE=edge"><title>GetWeather</title><link rel="stylesheet" href=""></h' +
        'ead><body><h1>HelloWorld ! ! !</h1><form action="" method="post">City: <input n' +
        'ame="city"> <br /><input type="submit" value="Get Weather" /></form>';
    if(weatherData){
        page+=`<h1>Weather Info</h1><p>${weatherData}</p></body></html>`;
    }
    res.end(page);
}

function parseWeather(weatherResponse,res){
    var weatherData="";
    weatherResponse.on("data",function (chunk) {
        weatherData+=chunk;
    });
    weatherResponse.on("end",function () {
        sendResponse(weatherData,res);
    })
}
function getWeather(city,res){
    console.log(city.city);
    var options={
        host:"openweathermap.org",
        path:"/find/?q="+city.city
    };
    http.request(options,function(weatherResponse){
        parseWeather(weatherResponse,res);
    }).end();
}
http.createServer((req,res)=>{
    if(req.method=="POST"){
        var reqData="";
        req.on("data",function(chunk){
            reqData+=chunk;
        });
        req.on("end",()=>{
            var postParams=qString.parse(reqData);
            getWeather(postParams,res);
        });
    }else{
        sendResponse(null,res);
    }
  console.log("Look me,I succeed !!!");

}).listen(8080);

  2、结果如下(没有具体的将天气信息抽取出来,将外源整个响应页面全部拿了过来):

 

转载于:https://www.cnblogs.com/realsoul/p/5642587.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值