VUE与IDEL解决跨域问题

前言

跨域是浏览器对ajax请求的限制
跨域:指的是浏览器不能执行其他网站的脚本。它是由浏览器的同源策略造成的,是浏览器对js施加的安全限制。(ajax可以)
同源策略:是指协议,域名,端囗都要相同,其中有一个不同都会产生跨域;
	跨域请求流程:
非简单请求(PUT、DELETE)等,需要先发送预检请求
   -----1、预检请求、OPTIONS ------>
   <----2、服务器响应允许跨域 ------
浏览器 |                               |  服务器
   -----3、正式发送真实请求 -------->
   <----4、响应数据   --------------

跨域的解决方案
解决方案1:
在这里插入图片描述
解决方案二:为在服务端2配置允许跨域
在响应头中添加:参考:https://blog.csdn.net/qq_38128179/article/details/84956552

  • Access-Control-Allow-Origin : 支持哪些来源的请求跨域
  • Access-Control-Allow-Method : 支持那些方法跨域
  • Access-Control-Allow-Credentials :跨域请求默认不包含cookie,设置为true可以包含cookie
  • Access-Control-Expose-Headers : 跨域请求暴露的字段
  • CORS请求时,XMLHttpRequest对象的getResponseHeader()方法只能拿到6个基本字段:
    Cache-Control、Content-Language、Content-Type、Expires、Last-Modified、Pragma
    如果想拿到其他字段,就必须在Access-Control-Expose-Headers里面指定。
  • Access-Control-Max-Age :表明该响应的有效时间为多少秒。在有效时间内,浏览器无须为同一请求再次发起预检请求。请注意,浏览器自身维护了一个最大有效时间,如果该首部字段的值超过了最大有效时间,将失效

java后台解决方法:在网关中定义“GulimallCorsConfiguration”类,该类用来做过滤,允许所有的请求跨域。

package com.atguigu.gulimall.gateway.config;

@Configuration // gateway
public class GulimallCorsConfiguration {
    
    

    @Bean // 添加过滤器
    public CorsWebFilter corsWebFilter(){
    
    
        // 基于url跨域,选择reactive包下的
        UrlBasedCorsConfigurationSource source=new UrlBasedCorsConfigurationSource();
        // 跨域配置信息
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        // 允许跨域的头
        corsConfiguration.addAllowedHeader("*");
        // 允许跨域的请求方式
        corsConfiguration.addAllowedMethod("*");
        // 允许跨域的请求来源
        corsConfiguration.addAllowedOrigin("*");
        // 是否允许携带cookie跨域
        corsConfiguration.setAllowCredentials(true);
        
       // 任意url都要进行跨域配置
        source.registerCorsConfiguration("/**",corsConfiguration);
        return new CorsWebFilter(source);
    }
}

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/fen_dou_shao_nian/article/details/117532640