什么是跨域?
跨域(Cross-Origin)指的是在 Web 开发中,浏览器的同源策略(Same-Origin Policy)限制了一个网页中加载其他域名下资源的能力。具体来说,同源策略指的是当浏览器执行一个跨域请求时,只有当该请求的协议、域名、端口号三者都与当前页面相同才会被允许。
解决方案:CORS、JSONP
CORS:翻译过来就是跨域资源共享
前端:
解决跨域常用方法:
一、VUE中常用proxy来解决跨域问题
1、在vue.config.js中设置如下代码片段
module.exports = {
dev: {
// Paths
assetsSubDirectory: 'static',
assetsPublicPath: '/',
proxyTable: { // 配置跨域
'/api':{
target:`http://www.baidu.com`, //请求后台接口
changeOrigin:true, // 允许跨域
pathRewrite:{
'^/api' : '' // 重写请求
}
}
},
}
2、创捷axioss实例时,将baseUrl设置为 ‘/api’
const http = axios.create({
timeout: 1000 * 1000000,
withCredentials: true,
BASE_URL: '/api'
headers: {
'Content-Type': 'application/json; charset=utf-8'
}
})
二、JSONP解决跨域
Jsonp(JSON with Padding) 是 json 的一种”使用模式”,可以让网页从别的域名(网站)那获取资料,即跨域读取数据。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<div id="textID"></div>
<script type="text/javascript">
function text_jsonp(req){
// 创建script的标签
var script = document.createElement('script');
// 拼接 url
var url = req.url + '?callback=' + req.callback.name;
// 赋值url
script.src = url;
// 放入头部
document.getElementsByTagName('head')[0].appendChild(script);
}
</script>
</body>
</html>
后端:
SpringBoot项目中解决跨域的三种解决方案
1.在目标方法或者controller类上加@CrossOrigin注解
2.添加CORS过滤器
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 CorsFilterConfig { // 当前跨域请求最大有效时长。这里默认1天 private static final long MAX_AGE = 24 * 60 * 60; @Bean public CorsFilter corsFilter() { UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); CorsConfiguration corsConfiguration = new CorsConfiguration(); corsConfiguration.addAllowedOrigin("*"); // 1 设置访问源地址 corsConfiguration.addAllowedHeader("*"); // 2 设置访问源请求头 corsConfiguration.addAllowedMethod("*"); // 3 设置访问源请求方法 corsConfiguration.setMaxAge(MAX_AGE); source.registerCorsConfiguration("/**", corsConfiguration); // 4 对接口配置跨域设置 return new CorsFilter(source); } }
3.实现WebMvcConfigurer,重写addCorsMappings方法
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 CrosConfiguration implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedOriginPatterns("*") .allowedMethods("GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS") .allowCredentials(true) .maxAge(3600) .allowedHeaders("*"); } }
年少轻狂,总以为天下事竭力有为。人事尽时,终感力不能及。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~