Roma
世界已黑白,此人已成仙。

年少轻狂,总以为天下事竭力有为。人事尽时,终感力不能及。
posts - 329,comments - 0,views - 13012

什么是跨域?

跨域(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("*");
    }

}
复制代码

 



posted on   罗|马  阅读(101)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

Live2D
欢迎阅读『解决跨域问题』
点击右上角即可分享
微信分享提示