在项目部署过程中,若部署服务器处于内网环境,则无法调用高德服务。需要通过搭建代理实现请求的转发,从而获取到在线服务内容。下面的记录解决了内网服务器访问高德地图服务的问题。
一、所需设备
- 内网服务器(项目所需部署环境,不通公网)
- 外网服务器(前置机),需要一台能够访问公网的服务器转发我们的请求
二、代理流程
1、修改前端:地图服务请求地址
原地址:
<script type="text/javascript"
src="https://webapi.amap.com/maps?v=1.4.15&key=****************************&plugin=AMap.MarkerClusterer,AMap.Geocoder"></script>
把指向高德服务的地址修改为:内网服务器地址。此时接口请求仍然不通,因为内网服务器没有此地图服务。
<script type="text/javascript"
src="http://171.11.12.121:60000/web1maps?v=1.4.15&key=****************************&plugin=AMap.MarkerClusterer,AMap.Geocoder"></script>
2、内网服务器配置nginx
前端请求发送到内网服务器后,通过nginx反向代理,监听请求端口60000,将请求转发至前置机(需要打通内网服务器与外网服务器(前置机)之间的通信)
此时请求仍然不通,因为前置机同样没有地图服务。
注意保持端口通信正常
内网服务器nginx配置如下
server {
listen 60000; //通过端口监听前端请求
server_name localhost;
location /web1 {
proxy_pass http://130.12.11.23:10010/web1; //转发请求至前置机地址
}
location /web2 {
proxy_pass http://130.12.11.23:10010/web2;
}
location /web3 {
proxy_pass http://130.12.11.23:10010/web3;
}
location /web4 {
proxy_pass http://130.12.11.23:10010/web4;
}
location /web5 {
proxy_pass http://130.12.11.23:10010/web5;
}
}
3、前置机配置nginx
请求转发至前置机后,再通过前置机的nginx做反向代理,把请求转发到高德服务器上,从而获取高德官方的服务数据。
前置机nginx配置如下
server {
listen 10010;
server_name localhost;
location /web1 {
proxy_pass https://webapi.amap.com/;
}
location /web2 {
proxy_pass http://vdata.amap.com/;
}
location /web3 {
proxy_pass http://restapi.amap.com/;
}
location /web4 {
proxy_pass http://vector.amap.com/;
}
location /web5 {
proxy_pass http://lbs.amap.com/;
}
}
至此!我们已经可以从内网发出请求,获取到高德官方的js文件
4、高德自调用接口拦截
在启用高德地图服务的过程中,高德会自调用一些高德服务,非前端主动请求。此时,我们需要把这些自调用的请求拦截下来,转发到我们的内网服务器上。然后按照前面的流程再走一遍。
这里我们会用到拦截器:ajaxhook.js
ajaxhook源码:github地址(内有详细介绍)
高德自调用的接口地址常用的就是下面拦截的这些,全部做了代理基本上就够了。
前端添加拦截器,全局拦截所有请求,筛选出高德的接口,并做转发。代码如下:
<script src="../static/js/ajaxhook.min.js"></script>
<script>
ah.proxy({
onRequest: (config, handler) => {
// console.log(config.url)
if (config.url.toString().search('https://vdata.amap.com') != -1) {
config.url = 'http://171.11.12.121:60000/web2' + config.url.split('vdata.amap.com/')[1];
console.log(config.url)
} else if (config.url.toString().search('http://restapi.amap.com') != -1) {
config.url = 'http://171.11.12.121:60000/web3' + config.url.split('restapi.amap.com/')[1];
console.log(config.url)
} else if (config.url.toString().search('http://vector.amap.com') != -1) {
config.url = 'http://171.11.12.121:60000/web4' + config.url.split('vector.amap.com/')[1];
console.log(config.url)
} else if (config.url.toString().search('http://lbs.amap.com') != -1) {
config.url = 'http://171.11.12.121:60000/web5' + config.url.split('lbs.amap.com/')[1];
console.log(config.url)
}
handler.next(config);
},
onError: (err, handler) => {
console.log(err.type)
handler.next(err)
},
onResponse: (response, handler) => {
// console.log(response.response)
handler.next(response)
}
})
</script>