Springboot跨域處理的多種方式小結(jié)
測試工具 IDEA
什么是跨域
當一臺服務(wù)器資源從另一臺服務(wù)器(不同 的域名或者端口)請求一個資源或者接口,就會發(fā)起一個跨域 HTTP 請求。
瀏覽器出于安全考慮,會限制跨域訪問,就是不允許跨域請求資源,要求協(xié)議,IP和端口必須都相同,其中有一個不同就會產(chǎn)生跨域問題,這就是同源策略。
跨域舉例
請求方 | 響應(yīng)方 | 是否跨域 | 原因 |
---|---|---|---|
http://www.ming.com | http://www.ming.com/test.html | 否 | 協(xié)議、域名、端口相同 |
http://www.ming.com | https://www.ming.com/test.html | 是 | 協(xié)議不同 |
http://www.ming.com | http://www.minggod.com/test.html | 是 | 主域名不同 |
http://www.ming.com | http://haha.ming.com/test.html | 是 | 主域名相同、子域名不同 |
http://www.ming.com:8080 | http://www.ming.com:8090/test.html | 是 | 端口不同 |
跨域訪問實例
后端測試代碼
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class CorsController { @GetMapping("/cors") public String hello(){ return "hello cors"; } }
用瀏覽器打開,我這里配置的端口是8090
在前端項目中用axios訪問時
<template> <span>跨域請求:{{result}}</span> </template> <script> import axios from 'axios'; export default { name: "Cors", data(){ return { result:"" } }, methods:{ getTest(){ axios.get("http://localhost:8090/cors").then(res=>{ console.log(res.data) this.result=res.data }) } }, created() { this.getTest(); } } </script> <style scoped> </style>
報錯中的關(guān)鍵詞
Access-Control-Allow-Origin
跨域處理(后端)
說明:
這里是針對Springboot 2.4.0以后的寫法,之前的版本寫法是.allowedOrigins(*)
2.4.0之后會報錯替換成.allowedOriginPatterns即可
代碼中會有注釋說明
1.添加跨域配置類
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 GlobalCorsConfig { @Bean public CorsFilter corsFilter() { //1. 添加 CORS配置信息 CorsConfiguration config = new CorsConfiguration(); //放行哪些原始域 config.addAllowedOriginPattern("*");//2.4.0后的寫法 // config.addAllowedOrigin("*"); //是否發(fā)送 Cookie config.setAllowCredentials(true); //放行哪些請求方式 config.addAllowedMethod("*"); //放行哪些原始請求頭部信息 config.addAllowedHeader("*"); //暴露哪些頭部信息 config.addExposedHeader("*"); //2. 添加映射路徑 UrlBasedCorsConfigurationSource corsConfigurationSource = new UrlBasedCorsConfigurationSource(); corsConfigurationSource.registerCorsConfiguration("/**",config); //3. 返回新的CorsFilter return new CorsFilter(corsConfigurationSource); } }
重啟后端服務(wù)后,刷新前端頁面正常訪問,效果如下
2. 重寫WebMvcConfigurer
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 CorsConfig implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") //是否發(fā)送Cookie .allowCredentials(true) //放行哪些原始域 //.allowedOrigins("*") .allowedOriginPatterns("*")//2.4.0后的寫法 .allowedMethods(new String[]{"GET", "POST", "PUT", "DELETE"}) .allowedHeaders("*") .exposedHeaders("*"); } }
3. 注解 @CrossOrigin
類上注解
@RestController @CrossOrigin("*") public class CorsController { @GetMapping("/cors") public String hello(){ return "hello cors"; } }
方法上注解
方法可以單獨跨域,沒有 @CrossOrigin(“*”) 注解的方法則不行
import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class CorsController { @GetMapping("/cors") @CrossOrigin("*") public String hello(){ return "hello cors"; } @GetMapping("/cors1") public String hello1(){ return "hello cors1"; } }
4.自定義過濾器
可以正??缬?/p>
import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Component; @Component public class MyCorsFilter implements Filter { public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletResponse response = (HttpServletResponse) res; HttpServletRequest httpServletRequest = (HttpServletRequest) req; response.setHeader("Access-Control-Allow-Origin", httpServletRequest.getHeader("origin")); response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, HEAD"); response.setHeader("Access-Control-Max-Age", "3600"); response.setHeader("Access-Control-Allow-Headers", "access-control-allow-origin, authority, content-type, version-info, X-Requested-With"); response.setHeader("Access-Control-Allow-Credentials", "true"); chain.doFilter(req, res); } public void init(FilterConfig filterConfig) {} public void destroy() {} }
5.手動設(shè)置響應(yīng)頭(局部跨域)
此方案聽說可以用,但明哥自己測試了,不能用,依然有問題,不建議!
@GetMapping("/cors1") public String hello1(HttpServletResponse response){ response.addHeader("Access-Allow-Control-Origin","*"); return "hello cors1"; }
小結(jié)
這節(jié)總結(jié)了“ Springboot跨域處理 ”,希望能對大家有所幫助。
到此這篇關(guān)于Springboot跨域處理的幾種方式的文章就介紹到這了,更多相關(guān)Springboot跨域處理內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
使用idea創(chuàng)建web框架和配置struts的方法詳解
這篇文章主要介紹了使用idea創(chuàng)建web框架和配置struts的方法,本文給大家介紹的非常詳細,對大家的學(xué)習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-09-09SpringBoot基于Minio實現(xiàn)分片上傳、斷點續(xù)傳的實現(xiàn)
本文主要介紹了SpringBoot基于Minio實現(xiàn)分片上傳、斷點續(xù)傳的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學(xué)習或者工作具有一定的參考學(xué)習價值,需要的朋友們下面隨著小編來一起學(xué)習學(xué)習吧2023-08-08Quarkus集成open api接口使用swagger ui展示
這篇文章主要為大家介紹了Quarkus集成open?api接口使用swagger?ui的展示示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步2022-02-02SpringBoot項目導(dǎo)入aliyun oss starter依賴后啟動報錯問題
這篇文章主要介紹了SpringBoot項目導(dǎo)入aliyun oss starter依賴后啟動報錯問題及解決方案,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-01-01