前后端分离引发的跨域问题解决

最近在进行公司项目的前后端分离,碰到的一些跨域问题,记录一下这些问题。
既然是问题,我们首先得知道什么是跨域问题?

跨域:所谓在同一个讲大白话就是你即将访问的页面所使用的协议、主机、端口都是相同的。不同协议、主机、端口的链接进行访问就属于跨域。

跨域问题来源于浏览器的同源策略,浏览器在进行请求时会根据是否同源进行安全限制。
不同源会产生以下一些限制

  1. 无法读取不同源界面的cookies、localstorge等
  2. 无法发送请求

回归正题,跨域解决主要有两个方面,一个是后端接口进行跨域处理。另一个在前端进行请求头部处理,加上跨域的请求头部。

后端的处理方式

//方式1
在对应的方法上加@CrossOrigin
@CrossOrigin
public class LoginRestController {}

//方式2 全局配置跨域
@Configuration
public class CrosConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
       registry.addMapping("/**")  //配置允许跨域访问的请求
       .allowedOrigins("*")            
       .allowCredentials(true)       //配置允许cookies通过
       .allowedHeaders("*")		//配置Header
       .allowedMethods("GET", "POST"); //配置HTTP请求的方式
    }
}

//方式3 配置speingmvc的过滤器
@Component
public class CORSFilter implements Filter {
 
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		//*号表示对所有请求都允许跨域访问
        HttpServletResponse res = (HttpServletResponse) response;
        res.addHeader("Access-Control-Allow-Credentials", "true");
        res.addHeader("Access-Control-Allow-Origin", "*");
        res.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");
        res.addHeader("Access-Control-Allow-Headers", "Content-Type,X-CAF-Authorization-Token,sessionToken,X-TOKEN");
        if (((HttpServletRequest) request).getMethod().equals("OPTIONS")) {
            response.getWriter().println("Success");
            return;
        }
        chain.doFilter(request, response);
    }
 
    @Override
    public void destroy() {
 
    }
 
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
 
    }
}

注册跨域配置

@Configuration
public class CorsConfig {
 
    @Bean
    public CorsFilter corsFilter() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedOrigin("*");
        corsConfiguration.addAllowedHeader("*");
        corsConfiguration.addAllowedMethod("*");
        corsConfiguration.setAllowCredentials(true);
        UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();
        urlBasedCorsConfigurationSource.registerCorsConfiguration("/**", corsConfiguration);
        return new CorsFilter(urlBasedCorsConfigurationSource);
    }
 
}

前端的处理方式

  1. axios 封装
import axios from 'axios'

export function request (config) {
 // 1.创建axios的实例
 const instance = axios.create({
   baseURL: 'http://localhost:8000',
   timeout: 5000,
   withCredentials: true
 })

 //  2.添加拦截器
 instance.interceptors.request.use(config => {
   console.log('请求发送', config)
   return config
 }, error => {
   console.log(error)
 })
 instance.interceptors.response.use(res => {
   console.log(res.data)
   return res.data
 }, error => {
   console.log(error)
 })

 //  3 返回axios实例
 return instance(config)
}

2.使用

data()
{let header =   {
  "X-Requested-Whit": "XMLHttpRequest",
  "Content-Type": "text/json;charset=utf-8",
  "Access-Control-Allow-Origin": "*",
  'Access-Control-Allow-Headers': "Authorization,Accept,Origin,DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range",
  'Access-Control-Allow-Methods': "GET,POST,OPTIONS,PUT,DELETE,PATCH"
}
return header
},
mounted(){
	let that = this.header;
	request({
      url: '/dmp/login',
      method: 'Get',
      headers:that.header,
      params: {
        dpToken: this.$route.query.dpToken,
        dpSign: this.$route.query.dpSign
      }
    }).then(function (res) {
      if (res.success) {
      
    }).catch(function (error) {
      console.log(error)
    })
    console.log('===================>', s)
  }
}

借鉴大佬的文章:https://blog.csdn.net/xhaimail/article/details/107909759

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Rio_NP

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值