詳解Spring Boot 2.0.2+Ajax解決跨域請(qǐng)求的問題
問題描述
后端域名為A.abc.com,前端域名為B.abc.com。瀏覽器在訪問時(shí),會(huì)出現(xiàn)跨域訪問。瀏覽器對(duì)于javascript的同源策略的限制。
HTTP請(qǐng)求時(shí),請(qǐng)求本身會(huì)返回200,但是返回結(jié)果不會(huì)走success,并且會(huì)在瀏覽器console中提示:
已攔截跨源請(qǐng)求:同源策略禁止讀取位于 https://www.baidu.com/ 的遠(yuǎn)程資源。(原因:CORS 頭缺少 ‘Access-Control-Allow-Origin')。
解決方案
1.jsonp
2.引用A站的js
3.Nginx做A站的反向代理
4.后端服務(wù)放開跨域請(qǐng)求
其中,以最后兩種見常。
詳細(xì)方案
本文主要描述第四種解決方案:后端服務(wù)放開跨域請(qǐng)求。
spring boot中放開跨域請(qǐng)求很簡(jiǎn)單。
1.增加一個(gè)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日
*/
@Configuration
public 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訪問可以正常進(jìn)行了,但是會(huì)不會(huì)有什么問題呢?
對(duì)于大部分網(wǎng)站依然需要使用cookie作為前后端傳輸數(shù)據(jù)的媒介,然而默認(rèn)非同源請(qǐng)求是不攜帶cookie信息的。
2.服務(wù)端允許跨域攜帶cookie信息
在spring boot2.0.2中,允許跨域設(shè)置比較簡(jiǎn)單,只需增加一個(gè)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日
*/
@Configuration
public 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);
}
}
增加信息后,在前端依然需要調(diào)整AJAX請(qǐng)求,才能在非同源請(qǐng)求中攜帶cookie信息。
3.前端調(diào)整
$.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('服務(wù)器發(fā)生錯(cuò)誤!');
}
});
此時(shí),當(dāng)前端向后端服務(wù)做跨域請(qǐng)求時(shí),增加
xhrFields:{
withCredentials:true
},
就會(huì)帶上cookie信息了,同理會(huì)帶上token/sessionID等等內(nèi)容。
測(cè)試方法
spring boot中增加一個(gè)controller
@Controller
public 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;
}
}
增加一個(gè)index.html,來訪問跨域訪問。
<html>
<head>
<meta charset="utf-8">
<title>跨域請(qǐng)求</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文件可以單獨(dú)本地訪問即可出現(xiàn)效果,并不一定要形成服務(wù)訪問。
當(dāng)服務(wù)端不允許跨域訪問時(shí),html文件訪問均報(bào)錯(cuò),并調(diào)用失敗。
當(dāng)服務(wù)端允許跨域訪問時(shí),html請(qǐng)求訪問成功。
當(dāng)服務(wù)端開啟cookie傳遞,并在html文件中增加 xhrFields參數(shù)時(shí),session生效。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- SpringBoot解決跨域請(qǐng)求攔截問題代碼實(shí)例
- Springboot解決ajax+自定義headers的跨域請(qǐng)求問題
- 詳解springboot設(shè)置cors跨域請(qǐng)求的兩種方式
- vue+springboot實(shí)現(xiàn)項(xiàng)目的CORS跨域請(qǐng)求
- Spring Boot Web應(yīng)用開發(fā) CORS 跨域請(qǐng)求支持
- spring boot配合前端實(shí)現(xiàn)跨域請(qǐng)求訪問
- 詳解SpringBoot多跨域請(qǐng)求的支持(JSONP)
- Spring Boot設(shè)置支持跨域請(qǐng)求過程詳解
相關(guān)文章
基于JavaSwing+mysql開發(fā)一個(gè)學(xué)生社團(tuán)管理系統(tǒng)設(shè)計(jì)和實(shí)現(xiàn)
項(xiàng)目使用Java swing+mysql開發(fā),可實(shí)現(xiàn)基礎(chǔ)數(shù)據(jù)維護(hù)、用戶登錄注冊(cè)、社團(tuán)信息列表查看、社團(tuán)信息添加、社團(tuán)信息修改、社團(tuán)信息刪除以及退出注銷等功能、界面設(shè)計(jì)比較簡(jiǎn)單易學(xué)、適合作為Java課設(shè)設(shè)計(jì)以及學(xué)習(xí)技術(shù)使用,需要的朋友參考下吧2021-08-08
解決Eclipse配置Tomcat出現(xiàn)Cannot create a server using the selected
這篇文章主要介紹了解決Eclipse配置Tomcat出現(xiàn)Cannot create a server using the selected type錯(cuò)誤的相關(guān)資料,需要的朋友可以參考下2017-02-02
String類型傳遞是值傳遞,char[]類型傳遞是引用傳遞的實(shí)現(xiàn)
下面小編就為大家?guī)硪黄猄tring類型傳遞是值傳遞,char[]類型傳遞是引用傳遞的實(shí)現(xiàn)。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看不2016-09-09
synchronized?和?Lock?的異同點(diǎn)(如何讓選擇)
這篇文章主要介紹了?synchronized和Lock的異同點(diǎn)(如何讓選擇),文章圍繞主題展開詳細(xì)的內(nèi)容介紹,具有一定的參考價(jià)值,需要的小伙伴可以參考一下2022-09-09
SpringBoot詳解如果通過@Value注解給靜態(tài)變量注入值
這篇文章主要介紹了springboot如何通過@Value給靜態(tài)變量注入值,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-06-06
springboot結(jié)合mybatis操作事務(wù)配置的處理
在操作數(shù)據(jù)庫(kù)的時(shí)候,經(jīng)常會(huì)使用事務(wù)的處理,本文主要介紹了springboot結(jié)合mybatis操作事務(wù)配置的處理,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2024-07-07

