CORS跨域問題常用解決方法程式碼例項
阿新 • • 發佈:2020-11-17
一 後端伺服器使用過濾器
新建過濾器:
/** * 解決跨域 */ public class AccessControlAllowOriginFilter implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest servletRequest,ServletResponse servletResponse,FilterChain filterChain) throws IOException,ServletException { System.out.println("解決跨域請求"); HttpServletResponse response = (HttpServletResponse) servletResponse; response.setHeader("Access-Control-Allow-Origin","*");//允許所有網站跨域訪問 response.setHeader("Access-Control-Allow-Methods","POST,GET,OPTIONS,DELETE"); response.setHeader("Access-Control-Allow-Credentials","true"); //這裡如果前端請求header首字母是小寫也是不行得,所以大小寫都寫上就沒問題了 response.setHeader("Access-Control-Allow-Headers","access-control-allow-origin,content-type,x-requested-with,Content-Type,Access-Control-Allow-Headers,Content-Length,Accept,Authorization,X-Requested-With"); filterChain.doFilter(servletRequest,response); } @Override public void destroy() {} }
前端header需要新增:
$.ajax( { url : 'http://c2.zhuzher.com/pdm/know/active?hotelid=808047&sdate=2019-11-09&edate=2019-11-11',beforeSend: function (xhr) { xhr.setRequestHeader("Access-Control-Allow-Origin","*"); //設定跨域訪問資訊 xhr.setRequestHeader("Content-Type","application/json;charset=utf-8"); },type : 'get',dataType : 'json',data:{},success : function(data) { alert(1111); } });
二 後端介面springboot/springmvc使用註解
springMVC的版本要在4.2或以上版本才支援@CrossOrigin ;
方法需要指明Get或者POST才行:
三 本地nginx反向代理(推薦)
本地下載解壓nginx,新增一個server配置檔案:
注意,如果是放在nginx的html目錄下一般是不需要加跨域配置的,否則會報配置多餘錯誤
每次可先直接使用試試,不行再加下面add_header等配置.
###start跨域支援配置#### add_header Access-Control-Allow-Origin '*'; add_header Access-Control-Allow-Headers Accept,Origin,X-Requested-With,If-Modified-Since,Last-Modified,Content-Range,Range,Content-Description,Content-Disposition; add_header Access-Control-Allow-Methods GET,POST,PUT,DELETE,OPTIONS; add_header Access-Control-Request-Headers Content-Disposition; add_header Access-Control-Allow-Credentials true; ###end ### server { listen 80; server_name 127.0.0.1; #charset koi8-r; #access_log logs/host.access.log main; location / { root html; index index.html index.htm; } #自定義本地路徑,代理轉發請求 location /pdm { proxy_pass http://c2.zhuzher.com/pdm; } } server { listen 8081; server_name 127.0.0.1; #charset koi8-r; #access_log logs/host.access.log main; location / { root html; index index.html index.htm; } #自定義本地路徑,代理轉發請求 location /pdm { proxy_pass http://c2.zhuzher.com/pdm; charset utf-8; # proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } }
專案裡面直接呼叫配置的8081埠就可以了:
api.get('//localhost:8081/pdm/user/login',data)
注意這裡還有一點需要注意,如果Content-Type是 application/json的話是無法傳送跨域請求的,這裡提供一種解決辦法,就是介面前端請求type改成
'Content-Type':'text/plain'
傳送資料轉成字串:
JSON.stringify(data)
後端介面用String接受資料,然後再轉成物件就可以了:
@PostMapping("/distributeBatch") public ResMsg distributeSaleBatch(@RequestBody String params){ System.out.println(params); //Integer user_id,Integer customer_id //Gson 字串轉物件 List<Map<String,Integer>> fromJson = new Gson().fromJson(params,new TypeToken<List<Map<String,Integer>>>() { }.getType()); System.out.println(new Gson().toJson(fromJson)); return registeredCustomerService.distributeSaleBatch(fromJson); }
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。