如何与外部源交互

一、原理

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

All rights reserved please indicate the source if reprint---吓尿了的大肥鼠
原文地址:https://www.cnblogs.com/realsoul/p/5642587.html