国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 開發 > Java > 正文

詳解Spring Boot 2.0.2+Ajax解決跨域請求的問題

2024-07-14 08:43:58
字體:
來源:轉載
供稿:網友

問題描述

后端域名為A.abc.com,前端域名為B.abc.com。瀏覽器在訪問時,會出現跨域訪問。瀏覽器對于javascript的同源策略的限制。

HTTP請求時,請求本身會返回200,但是返回結果不會走success,并且會在瀏覽器console中提示:

已攔截跨源請求:同源策略禁止讀取位于 https://www.baidu.com/ 的遠程資源。(原因:CORS 頭缺少 ‘Access-Control-Allow-Origin')。

解決方案

1.jsonp

2.引用A站的js

3.Nginx做A站的反向代理

4.后端服務放開跨域請求

其中,以最后兩種見常。

詳細方案

本文主要描述第四種解決方案:后端服務放開跨域請求。

spring boot中放開跨域請求很簡單。

1.增加一個configuration類

import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.web.cors.CorsConfiguration;import org.springframework.web.cors.UrlBasedCorsConfigurationSource;import org.springframework.web.filter.CorsFilter;/** * 跨域訪問配置 * @author wencst * @creation 2017年8月18日 */@Configurationpublic class CustomCORSConfiguration { private CorsConfiguration buildConfig() { CorsConfiguration corsConfiguration = new CorsConfiguration(); corsConfiguration.addAllowedOrigin("*"); corsConfiguration.addAllowedHeader("*"); corsConfiguration.addAllowedMethod("*"); return corsConfiguration; } @Bean public CorsFilter corsFilter() { UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**", buildConfig()); return new CorsFilter(source); }}

增加此類以后,非同源http訪問可以正常進行了,但是會不會有什么問題呢?

對于大部分網站依然需要使用cookie作為前后端傳輸數據的媒介,然而默認非同源請求是不攜帶cookie信息的。

2.服務端允許跨域攜帶cookie信息

在spring boot2.0.2中,允許跨域設置比較簡單,只需增加一個configuration類即可。

import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.web.cors.CorsConfiguration;import org.springframework.web.cors.UrlBasedCorsConfigurationSource;import org.springframework.web.filter.CorsFilter;/** * 跨域訪問配置 * @author wencst * @creation 2017年8月18日 */@Configurationpublic class CustomCORSConfiguration { private CorsConfiguration buildConfig() { CorsConfiguration corsConfiguration = new CorsConfiguration(); corsConfiguration.addAllowedOrigin("*"); corsConfiguration.addAllowedHeader("*"); corsConfiguration.addAllowedMethod("*"); corsConfiguration.addExposedHeader("Content-Type"); corsConfiguration.addExposedHeader( "X-Requested-With"); corsConfiguration.addExposedHeader("accept"); corsConfiguration.addExposedHeader("Origin"); corsConfiguration.addExposedHeader( "Access-Control-Request-Method"); corsConfiguration.addExposedHeader("Access-Control-Request-Headers"); corsConfiguration.setAllowCredentials(true); return corsConfiguration; } @Bean public CorsFilter corsFilter() { UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**", buildConfig()); return new CorsFilter(source); }}

增加信息后,在前端依然需要調整AJAX請求,才能在非同源請求中攜帶cookie信息。

3.前端調整

$.ajax({ url: 'http://beta.roboming.com/api.php?s=/Public/AdminLogin.html', type: 'POST', async:true, xhrFields:{  withCredentials:true }, data: {  username:userName,  password:pwd }, success: function(respon){  console.log(respon);  var res=eval(respon); }, error: function(){  alert('服務器發生錯誤!'); }});

此時,當前端向后端服務做跨域請求時,增加

xhrFields:{  withCredentials:true},

就會帶上cookie信息了,同理會帶上token/sessionID等等內容。

測試方法

spring boot中增加一個controller

@Controllerpublic class LoginController { @RequestMapping(value = "setString") @ResponseBody public String setString(HttpServletRequest request, HttpServletResponse response,@RequestParam String value) { request.getSession().setAttribute("username", value); return "OK"; } @RequestMapping(value = "getString") @ResponseBody public String getString(HttpServletRequest request, HttpServletResponse response) { String username = (String)request.getSession().getAttribute("username"); return username; }}

增加一個index.html,來訪問跨域訪問。

<html><head><meta charset="utf-8"><title>跨域請求</title><script src="https://cdn.bootcss.com/jquery/1.10.2/jquery.min.js"></script></head><body><button onclick="set()">set</button><br><br><button onclick="get()">get</button><script>function set(){ $.ajax({ url:'http://wencst.vicp.net/setString?value=10', xhrFields:{  withCredentials:true }, success:function(result){ alert(result); } });}function get(){ $.ajax({ url:'http://wencst.vicp.net/getString', xhrFields:{  withCredentials:true }, success:function(result){ alert(result); } });}</script></body></html>

html文件可以單獨本地訪問即可出現效果,并不一定要形成服務訪問。

當服務端不允許跨域訪問時,html文件訪問均報錯,并調用失敗。

當服務端允許跨域訪問時,html請求訪問成功。

當服務端開啟cookie傳遞,并在html文件中增加 xhrFields參數時,session生效

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持VeVb武林網。


注:相關教程知識閱讀請移步到JAVA教程頻道。
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 横山县| 绵竹市| 嫩江县| 丰宁| 镶黄旗| 陆川县| 翁源县| 前郭尔| 南雄市| 灵山县| 彝良县| 太谷县| 乐陵市| 上高县| 乐安县| 陇川县| 青铜峡市| 高台县| 永泰县| 克拉玛依市| 长宁县| 扎鲁特旗| 金川县| 五莲县| 保山市| 神池县| 华蓥市| 通山县| 东丰县| 霍山县| 青阳县| 涿鹿县| 平南县| 大安市| 马山县| 东港市| 宝坻区| 弥渡县| 淅川县| 乐昌市| 永川市|