目前項目大多使用前后端分離的模式進行開發,跨域請求當然就是必不可少了,很多時候我們會使用在客戶端的ajax 請求中設置跨域請求,也有的在服務端設置跨域。但是有時候會遇到不使用ajax也沒有使用后端服務的情況(如:openlayers 加載本地的arcgis 瓦片數據),我們只需要進行一些靜態資源的獲取,於是我們把它交給了nginx 。
一、未配置跨域情況
看下面vue + openlayers 中讀取本地瓦片的配置
let layers_leshan = new TileLayer({
source: new XYZ({
crossOrigin: "anonymous",
projection: 'EPSG:4326',
url: '/image_map/_alllayers/',
tileUrlFunction: function (tileCoord, pixelRatio, proj) {
var x = 'C' + padLeft(tileCoord[1], 8, 16);
var y = 'R' + padLeft(tileCoord[2] -1, 8, 16);
var z = 'L' + padLeft(tileCoord[0], 2, 10);
var Newurl = '/image_map/_alllayers/' + z + '/' + y + '/' + x + '.png';
return Newurl;
}
}),
zIndex: -3,
visible: true
});
這里如果使用ajax,層層回調根本獲取不到數據,也許有大佬可以做到(只是我試了沒成功);當初我竟然將數據打包,然后放到nginx中來進行測試(哎),如下面是我的nginx 配置
- 這是配置的vue 項目build后的dist目錄映射
# 這個直接指向了我vue項目的dist目錄,用於nginx 加載讓其在同一個服務中來解決跨域問題
location /dist/{
root /YLKJPro/leshan_integrate_manage;
}
- 離線瓦片的配置為
location /image_map/{
root html;
}
其中瓦片目錄如下
二、nginx配置了跨域
最后找到了在nginx中配置允許服務端跨域的方法,將nginx中配置改為
location /image_map/{
### configuration with allow cross domain ##
add_header 'Access-Control-Allow-Origin' $http_origin always;
add_header 'Access-Control-Allow-Credentials' 'true' always;
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS' always;
add_header 'Access-Control-Allow-Headers' 'DNT,web-token,app-token,Authorization,Accept,Origin,Keep-Alive,User-Agent,X-Mx-ReqToken,X-Data-Type,X-Auth-Token,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range' always;
add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range' always;
if ($request_method = 'OPTIONS') {
add_header 'Access-Control-Max-Age' 1728000 always;
add_header 'Content-Type' 'text/plain; charset=utf-8' always;
add_header 'Content-Length' 0 always;
return 204;
}
root html;
}
vue 中配置改為
let layers_leshan = new TileLayer({
source: new XYZ({
crossOrigin: "anonymous",
projection: 'EPSG:4326',
url: 'http://localhost:808/image_map/_alllayers/',
tileUrlFunction: function (tileCoord, pixelRatio, proj) {
var x = 'C' + padLeft(tileCoord[1], 8, 16);
var y = 'R' + padLeft(tileCoord[2] -1, 8, 16);
var z = 'L' + padLeft(tileCoord[0], 2, 10);
var Newurl = 'http://localhost:808/image_map/_alllayers/' + z + '/' + y + '/' + x + '.png';
return Newurl;
}
}),
zIndex: -3,
visible: true
});
這樣就可以在vue項目中直接訪問到離線瓦片了,解決了由於跨域而需要在每次運行項目測試時,先build ,然后通過nginx對dist 的映射來進行項目測試(這個太過於麻煩)的問題。