服务器代理原理

服务器代理

原理:用自己的服务器发请求,请求别人服务器的数据,然后再将请求过来的数据分散开

request.js

const http = require('http');
const querystring = require('querystring');
const {readFile,writeFile}=require('./lib/file');

const server=http.createServer((req,res)=>{
    if (req.url == '/favicon.ico') return;
    console.log(`${req.method} ${req.headers.host}${req.url}`);

    res.writeHead(200,{"content-type":"text/html;charset=utf-8"});//设置响应头
    if(req.method==='GET'){
        switch(req.url){
            case '/':
                readFile('public','html','index.html').then(data=>{
                    res.end(data);
                }).catch(err=>{
                    res.end(err);
                });
                break;
            case '/weather':
                getData(res);
                break;
        }
    }else{

    }
});

server.listen(8088,()=>{
    console.log('服务已经运行在 http://localhost:8088');
})


//获取天气预报数据的函数
function getData(response){
    let opt = {
        app: 'weather.future',
        weaid: 'hangzhou',
        appkey: '38926',
        sign: 'f8b4121c2d581be2623569b24f798dee',
        format: 'json'
    };
    
    const options = {
        hostname: 'api.k780.com', // 主机名
        port: 80, //端口
        path: `/?${querystring.stringify(opt)}`, //路径
        method: 'GET' // 请求方式
    };
    
    const req = http.request(options, (res) => {
        let data = '';
        res.setEncoding('utf8'); // 设置字符集
        res.on('data', (chunk) => {
            data += chunk; // 两次获得的数据进行拼接
        });
        res.on('end', () => {
            // 当数据响应结束后执行
            response.end(data);
        });
    });
    
    req.on('error', (e) => { // 错误事件 
        console.error(`problem with request: ${e.message}`);
    });
    
    req.end();
}

index.html

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>

<body>
    <script>
        $(function() {
            $.ajax({
                type: "get",
                url: "http://localhost:8088/weather",
                dataType: "json",
                success: function(response) {
                    console.log(response);
                }
            });
        });
    </script>
</body>

</html>

请求到数据
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值