創建過濾器解決跨域問題
(就是前后端在不同服務器上運行)注意:區域和全域只能選擇一種!!!
本文只講述了解決跨域問題的方法,不提供原始碼講解,
開啟跨域配置
如果使用了springsecurity則需要在securityconfig中添加 .cors()
全域開啟:
SecurityConfig:(隨便一個config都行,這里就先放在securityconfig里)
@Bean
public CorsFilter corsFilter() {
//創建CorsConfiguration物件后添加配置
CorsConfiguration config = new CorsConfiguration();
//設定放行哪些原始域,這里直接設定為所有
config.addAllowedOriginPattern("*");
//你可以單獨設定放行哪些原始域 config.addAllowedOrigin("http://localhost:2222");
//放行哪些原始請求頭部資訊
config.addAllowedHeader("*");
//放行哪些請求方式,*代表所有
config.addAllowedMethod("*");
//是否允許發送Cookie,必須要開啟,因為我們的JSESSIONID需要在Cookie中攜帶
config.setAllowCredentials(true);
//映射路徑
UrlBasedCorsConfigurationSource corsConfigurationSource = new UrlBasedCorsConfigurationSource();
corsConfigurationSource.registerCorsConfiguration("/**", config);
//回傳CorsFilter
return new CorsFilter(corsConfigurationSource);
}
區域開啟:在controller類上加注解@CrossOrigin( 可以詳細看注解里面的設定
@CrossOrigin
@RestController
@RequestMapping("/api/user")
public class AccountApiController {
}
設定前端發送的請求攜帶cookie
如果是自己寫的前端需要在發送每個請求的時候帶cookie資訊(自定義請求,開啟get、post請求時帶cookie)
function get(url,data, success){
$.ajax({
type: "get",
url: url,
data:data,
async: true,
dataType: 'json',
xhrFields: {
withCredentials: true //開啟攜帶cookie資訊,用于security識別用戶是否登錄
},
success: success
});
}
function post(url, data, success){
$.ajax({
type: "post",
url: url,
async: true,
data: data,
dataType: 'json',
xhrFields: {
withCredentials: true
},
success: success
});
}
//舉例:
function initUserInfo() {
get('http://localhost:8080/api/user/info', {},function (data) { //這里要加{},告訴data是空,否則會吧后面的當作data
if (data.code === 200) {
alert("登錄成功,歡迎" + data.data.username + "進入圖書管理系統!")
} else {
alert(data.reason)
window.location = "http://localhost:8080/login.html"
}
})
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/500961.html
標籤:其他
上一篇:這份工具清單,令Python 提速N倍,簡直太好用了
下一篇:實踐:二進制資料處理與封裝
