SpringBoot項(xiàng)目解決跨域的四種方案分享
測(cè)試是否跨域
可以在瀏覽器中隨便打開一個(gè)頁(yè)面的控制臺(tái),然后在控制臺(tái)中執(zhí)行下面這段代碼:
var xhr = new XMLHttpRequest()
xhr.open('GET', 'http://localhost:8080/user') // 替換請(qǐng)求的方法和地址
xhr.send()
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
console.log(xhr.responseText)
}
}如果出現(xiàn)了如下的輸出,代表確實(shí)有跨域

一、SpringBoot 配置 CORS 解決跨域
即在我們所有響應(yīng)頭配置允許跨域訪問(wèn),CORS也已經(jīng)成為主流的跨域解決方案。
- 在項(xiàng)目中創(chuàng)建一個(gè)新的配置文件
- 添加
@Configuration注解實(shí)現(xiàn)WebMvcConfigurer接口 - 重寫
addCorsMappings方法并設(shè)置允許跨域的代碼
具體代碼如下:
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**") // 所有接口
.allowCredentials(true) // 是否發(fā)送 Cookie
.allowedOriginPatterns("*") // 支持域
.allowedMethods("GET", "POST", "PUT", "DELETE") // 支持方法
.allowedHeaders("*")
.exposedHeaders("*");
}
}二、SpringBoot 通過(guò) CorsFilter 解決跨域
這種方式和上面的方式類似,也是通過(guò)Java Config的方式配置跨域訪問(wèn),具體代碼如下:
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;
@Configuration
public class MyCorsFilter {
@Bean
public CorsFilter corsFilter() {
// 1.創(chuàng)建 CORS 配置對(duì)象
CorsConfiguration config = new CorsConfiguration();
// 支持域
config.addAllowedOriginPattern("*");
// 是否發(fā)送 Cookie
config.setAllowCredentials(true);
// 支持請(qǐng)求方式
config.addAllowedMethod("*");
// 允許的原始請(qǐng)求頭部信息
config.addAllowedHeader("*");
// 暴露的頭部信息
config.addExposedHeader("*");
// 2.添加地址映射
UrlBasedCorsConfigurationSource corsConfigurationSource = new UrlBasedCorsConfigurationSource();
corsConfigurationSource.registerCorsConfiguration("/**", config);
// 3.返回 CorsFilter 對(duì)象
return new CorsFilter(corsConfigurationSource);
}
}三、SpringBoot 通過(guò)注解解決跨域
可以在我們的控制器類或控制器方法上添加,添加在類上表示里面所有方法都可跨域,添加在方法上表示指定方法可以跨域,具體代碼如下:
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/user")
@CrossOrigin
public class UserController {
@GetMapping
public String getAll() {
return "成功";
}
}四、通過(guò) nginx 配置 CORS 解決跨域
如果我們項(xiàng)目有用 nginx 做反向代理服務(wù)器時(shí),也可以在nginx中配置CORS來(lái)解決跨域,配置示例如下:
1.允許全部域名
server {
...
location / {
#允許 所有頭部 所有域 所有方法
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Headers' '*';
add_header 'Access-Control-Allow-Methods' '*';
#OPTIONS 直接返回204
if ($request_method = 'OPTIONS') {
return 204;
}
}
...
}2.允許指定域名
map $http_origin $corsHost {
default 0;
"~https://aa.cn" https://aa.cn;
"~https://bb.cn" https://bb.cn;
"~https://cc.cn" https://cc.cn;
}
server {
...
location / {
#允許 所有頭部 所有$corsHost域 所有方法
add_header 'Access-Control-Allow-Origin' $corsHost;
add_header 'Access-Control-Allow-Headers' '*';
add_header 'Access-Control-Allow-Methods' '*';
#OPTIONS 直接返回204
if ($request_method = 'OPTIONS') {
return 204;
}
}
...
}到此這篇關(guān)于SpringBoot項(xiàng)目解決跨域的四種方案分享的文章就介紹到這了,更多相關(guān)SpringBoot解決跨域內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Spring事務(wù)&Spring整合MyBatis的兩種方式
這篇文章主要介紹了Spring事務(wù)&Spring整合MyBatis的兩種方式,本文結(jié)合實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2023-02-02
關(guān)于@RequestParam的使用所遇到的404問(wèn)題
這篇文章主要介紹了關(guān)于@RequestParam的使用所遇到的404問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-08-08
Java正則表達(dá)式詳解及實(shí)用案例(附詳細(xì)代碼)
正則表達(dá)式是一種強(qiáng)大的字符串處理工具,用于匹配和解析文本,這篇文章主要給大家介紹了關(guān)于Java正則表達(dá)式詳解及實(shí)用案例的相關(guān)資料,本文通過(guò)代碼示例講解了正則表達(dá)式的基本語(yǔ)法規(guī)則,包括字符類、預(yù)定義字符類和數(shù)量詞,需要的朋友可以參考下2024-11-11
Spring下token過(guò)期時(shí)間分平臺(tái)(web和app)設(shè)置方法
本文詳細(xì)介紹了在Spring環(huán)境下,針對(duì)web端和APP端實(shí)現(xiàn)不同token過(guò)期時(shí)間的方法,通過(guò)整合SpringBoot、springSecurity和JWT框架,文章講解了登錄流程、JWT的基本組成以及token鑒權(quán)的核心步驟,需要的朋友可以參考下2024-10-10
Springboot項(xiàng)目監(jiān)聽器失效問(wèn)題解決
這篇文章主要介紹了Springboot項(xiàng)目監(jiān)聽器失效問(wèn)題解決,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-03-03
java設(shè)計(jì)模式學(xué)習(xí)之策略模式
這篇文章主要為大家詳細(xì)介紹了java設(shè)計(jì)模式學(xué)習(xí)之策略模式的相關(guān)資料,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-10-10
SpringBoot3.x循環(huán)依賴問(wèn)題解決方案
這篇文章主要介紹了SpringBoot3.x循環(huán)依賴的相關(guān)知識(shí),本文通過(guò)示例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2023-06-06

