node.JS之中转服务器

经过前面node的学习,我们对node已经有了一定的了解下面我直接上中转服务器实现过程和思路说明。

let http=require('http');
let https=require('https');
var iconv = require('iconv-lite');
let express=require('express');
let app=express();

app.use(express.json());
app.use(express.urlencoded({ extended: false }));

app.use('*',function(req,res,next){
    res.header('Access-Control-Allow-Origin','*');
    res.header('Access-Control-Allow-Credentials',' true');
    res.header('Access-Control-Allow-Methods','GET,PUT,POST,DELETE,OPTIONS');
    res.header('Access-Control-Allow-Headers','WWW-Authenticate,Authorization,Set-Cookie,X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version,name');
    next();
});

/*
    1.完成中转服务器的实现
    2.服务器需要支持http和https
*/
// let url="http://cache.video.iqiyi.com/jp/avlist/202861101/1/";

app.get('/',(req,response)=>{
    let obj={};
    let url=req.query.api+"&key="+req.query.key;
    console.log(url);
    //没有传递路径
    if(url==undefined){
        obj.code='600';
        obj.msg={infor:'使用方法错误',use:'http://localhost:9000?API=?'};
        response.send(JSON.stringify(obj));
        return;
    }

    //https请求
    if(url.indexOf('https')!=-1){
        https.get(url,function(res){
            // res.setEncoding('gbk');
            // let str='';
            let datas=[];
            res.on('data',chuck=>{
                // str+=chuck;
                datas.push(chuck);
            });
            res.on('end',function(){
                var decodedBody = iconv.decode(Buffer.concat(datas), 'GBK');
                console.log(decodedBody,typeof decodedBody);
                response.send(decodedBody);
            })
        });
    }else{
        getInfoFromServer(url,function(data){
            response.send(data);
        });
    }
});

app.listen('9000',err=>{
    if(!err){
        console.log('ther server is running on 9000.............');
    }
});

//向第三方服务器发起请求
function getInfoFromServer(url,fn){
    // let msg="";//保存数据
    let msg=[];
    http.get(url,res=>{
        //接收数据
        res.on('data',chuck=>{
            // msg+=chuck;
            msg.push(chuck);
        });
        res.on('end',()=>{
            // console.log(msg);
            //对字符集进行编码
            var decodedBody = iconv.decode(Buffer.concat(msg), 'utf-8');
            fn(decodedBody);
        });
        res.on('error',function(err){
            console.log('发送错误');
        });
    });
}

上面的方法可以实现对HTTP或HTTPS的请求处理,为了解决HTTPS加密返回数据乱码的问题,在接受的数据进行了编码处理。
上面的案例也只是介绍了get请求方式的处理post的请求方法一样,故这里就不在叙述了。

发布了35 篇原创文章 · 获赞 47 · 访问量 8608

猜你喜欢

转载自blog.csdn.net/qq_40665861/article/details/99481529