跨域解决方案

什么是跨域?

跨域就是:前端页面使用发送 AJAX 请求时,这个请求的目标地址与当前页的地址不同源。(协议、域名、端口不同)

跨域会产生什么问题?

浏览器将不会接受服务端的返回的响应。

解决方案:

1、SpringMVC中写好了CORS的跨域过滤器:CorsFilter。
增加配置类

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 CorsConfig {

    @Bean
    public CorsFilter corsFilter() {
        System.out.println("执行到cors过滤器");
        // 1、配置CORS跨域信息
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedOrigin("http://127.0.0.1:5500"); // 设置允许跨域的原始域名
        corsConfiguration.setAllowCredentials(true); //运行携带Cookie
        corsConfiguration.addAllowedMethod("*"); // 允许所有方法
        corsConfiguration.addAllowedHeader("*"); // 允许所有请求头

        // 2、初始化CORS配置源
        UrlBasedCorsConfigurationSource corsConfigurationSource = new UrlBasedCorsConfigurationSource();
        corsConfigurationSource.registerCorsConfiguration("/**", corsConfiguration);

        // 3、返回CORS过滤器
        return new CorsFilter(corsConfigurationSource);

    }

2、重写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 CorsConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowCredentials(true) //是否发送Cookie
                .allowedOrigins("*")
                .allowedMethods("GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS")
                .allowCredentials(true)
                .maxAge(3600)
                .allowedHeaders("*");
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值