使用SpringBoot開發前后端分離的應用,可以使用Nginx作為網關來統一解決跨域問題。這種好處是,可以不修改應用代碼的情況下,讓應用支持跨域。
對於很多不支持的跨域的網站,你也可以弄個Nginx給它“加個Buff”,也就可以進行跨域訪問了。 😆
Nginx配置(這個配置,可以解決 95% 以上的跨域問題)
server {
listen 80;
server_name localhost 127.0.0.1;
location / {
# 允許跨域請求的“域”
add_header 'Access-Control-Allow-Origin' $http_origin;
# 允許客戶端提交Cookie
add_header 'Access-Control-Allow-Credentials' 'true';
# 允許客戶端的請求方法
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, DELETE, PUT';
# 允許客戶端提交的的請求頭
add_header 'Access-Control-Allow-Headers' 'Origin, x-requested-with, Content-Type, Accept, Authorization';
# 允許客戶端訪問的響應頭
add_header 'Access-Control-Expose-Headers' 'Cache-Control, Content-Language, Content-Type, Expires, Last-Modified, Pragma';
# 處理預檢請求
if ($request_method = 'OPTIONS') {
# 預檢請求緩存時間
add_header 'Access-Control-Max-Age' 1728000;
add_header 'Content-Type' 'text/plain; charset=utf-8';
add_header 'Content-Length' 0;
return 204;
}
# SpringBoot 應用訪問路徑
proxy_pass http://127.0.0.1:8080;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_connect_timeout 600;
proxy_read_timeout 600;
}
}
關於Nginx的下載,配置,啟動等這些雜七雜八的東西,這里不多贅述,如果你還沒接觸過Nginx,現在就是個好機會,Nginx官網。
SpringBoot Controller
// 在 8080 端口 提供服務
@RequestMapping("/test")
@RestController
public class TestController {
@GetMapping("/cors")
public Object corsTest () {
return Collections.singletonMap("name", "SpringBoot中文社區");
}
}
測試
瀏覽器新開一個頁面就可以進行測試,主要能執行js。跨域嘛,只要是端口,url,協議。任意不同就可以了。
跨域失敗
直接請求SpringBoot服務(8080端口),跨域失敗。
跨域成功
請求Nginx網關服務(80端口),跨域成功