前端代码:
<!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>手机号查询</title>
</head>
<body>
<script>
axios.get('http://localhost:9000',{params:{
myUrl : `http://apis.juhe.cn/mobile/get?phone=15938335231&key=6033c85baa0ef963cb62430c1b23f171` //查询手机号的接口
}} ).then(({data}) => {
console.log(data);
});
</script>
</body>
</html>
服务器端代码:
let http=require('http');
let https=require('https');
var iconv = require('iconv-lite');//nodejs识别gbk
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
*/
app.get('/',(req,response)=>{
let obj={};
let url=req.query.myUrl;
console.log(url);
//没有传递路径
if(url==undefined){
obj.code='600';
obj.msg={infor:'使用方法错误',use:'http://localhost:9000?myUrl=?'};
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(){
response.send(msg);
})
});
}else{
getInfoFromServer(url,function(data){
console.log(data);
response.send(data);
});
}
});
app.listen('9000',err=>{
if(!err){
console.log('ther server is running on 9000.............');
console.log('you can use as :http://localhost:9000?myUrl=?');
}
});
//向第三方服务器发起请求
function getInfoFromServer(url,fn){
let msg=""; //保存数据
http.get(url,res=>{
//接收数据
res.on('data',chuck=>{
// msg+=chuck;
// msg.push(chuck);
msg+=chuck;
});
res.on('end',()=>{
// console.log(msg);
// var decodedBody = iconv.decode(Buffer.concat(msg), 'utf-8');
fn(msg);
});
});
}