zoukankan      html  css  js  c++  java
  • 如何与外部源交互

    一、原理

    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---吓尿了的大肥鼠
  • 相关阅读:
    Eclipse自动换行插件
    JAVA中super与this的区别
    外网访问PG数据库,如何赋予IP访问权限
    PostgreSQL环境变量与psql命令的替代作用
    \l 的使用
    一次生成任意多行数据的语句
    equals与==的区别
    PostgreSQL 名词理解EXPLAIN VERBOSE
    PG坑爹的数组定义
    【收藏】常用的ftp命令
  • 原文地址:https://www.cnblogs.com/realsoul/p/5642587.html
Copyright © 2011-2022 走看看