服务器代理
原理:用自己的服务器发请求,请求别人服务器的数据,然后再将请求过来的数据分散开
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>
请求到数据