前后端分离的跨域解决方案
聲明:
在以往的開發中,前后端分離也不是像現在這么熱門,所謂的前端工程師也只不過是寫好靜態頁面由Java工程師或者php工程師嵌入到頁面中進行開發,這或許加重了這些工程師的工作量,而且在樣式調試上由純html代碼到jsp,asp,php調試起來要兩個工程師一起商量著找問題,解決起來成本也很高。前后端分離,前端工程師不僅僅要負責展現,而且要編寫相應的代碼使得dom渲染,網絡交互都focus在前端工程師這里。這樣服務器端工程師則更加有精力來維護代碼的邏輯性,事務性,性能等。是啊,技術框架百花齊放的今天,前端也要mvc了。angular,vue等。下面我將自身實踐簡述如何解決跨域問題
跨域問題簡述(引用網絡上比較清晰的闡述表格)
第一種解決方案jsonp(不推薦使用)
這種方案其實我是不贊同的,第一,在編碼上jsonp會單獨因為回調的關系,在傳入傳出還有定義回調函數上都會有編碼的”不整潔”.簡單闡述jsonp能夠跨域是因為javascript的script標簽,通過服務器返回script標簽的code,使得該代碼繞過瀏覽器跨域的限制。并且在客戶端頁面按照格式定義了回調函數,使得script標簽返回實現調用
第二種方案,反向代理(推薦使用)
代理訪問其實在實際應用中有很多場景,在跨域中應用的原理做法為:通過反向代理服務器監聽同端口,同域名的訪問,不同路徑映射到不同的地址,比如,在nginx服務器中,監聽同一個域名和端口,不同路徑轉發到客戶端和服務器,把不同端口和域名的限制通過反向代理,來解決跨域的問題,案例如下:
server {listen 80;server_name domain.com;#charset koi8-r;#access_log logs/host.access.log main;location /client { #訪問客戶端路徑proxy_pass http://localhost:81;proxy_redirect default;}location /apis { #訪問服務器路徑rewrite ^/apis/(.*)$ /$1 break;proxy_pass http://localhost:82;} }- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
第三種方案在server設置header
通過設置server的header來設置瀏覽器對于服務器跨域的限制,具體實現如下:
//統一過濾器設置 public class DomainFilter implements Filter {@Overridepublic void init(FilterConfig filterConfig) throws ServletException {}@Overridepublic void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {HttpServletResponse response = (HttpServletResponse) res;response.setHeader("Access-Control-Allow-Origin", "*");response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");response.setHeader("Access-Control-Max-Age", "3600");response.addHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");chain.doFilter(req, res);}@Overridepublic void destroy() {} }//spring boot過濾器設置@Beanpublic FilterRegistrationBean filterRegistrationBean() {FilterRegistrationBean registrationBean = new FilterRegistrationBean();DomainFilter domainFilter = new DomainFilter();registrationBean.setFilter(domainFilter);List<String> urlPatterns = new ArrayList<String>();urlPatterns.add("/*");registrationBean.setUrlPatterns(urlPatterns);return registrationBean;}- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
總結
以上是生活随笔為你收集整理的前后端分离的跨域解决方案的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 用PC端Chrome浏览器进行模拟微信浏
- 下一篇: js-forEach 不能使用break