SpringBoot解决跨域(CROS)问题

本文介绍如何在SpringBoot项目中通过CorsConfig.java配置文件解决前端发起的跨域请求问题,提供详细的步骤和代码示例,确保跨域访问权限设置。

SpringBoot解决跨域问题(CROS)

问题:

前端请求后端出现下图类似问题:
在这里插入图片描述

Access to fetch at 'http://localhost:8081/user/page?pageNum=1&pageSize=2' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

解决:

再SpringBoot项目里面加上配置文件CorsConfig.java,重启之后即可实现跨域访问,不需要再在前端配置跨域设置。

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 {

    // 当前跨域请求最大有效时长(单位s)
    private static final long MAX_AGE = 24 * 60 * 60;
    
    @Bean
    public CorsFilter corsFilter() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedOrigin("*"); // 1、设置访问源地址
        corsConfiguration.addAllowedHeader("*"); // 2、设置访问源请求头
        corsConfiguration.addAllowedMethod("*"); // 3、设置访问源请求方法
        corsConfiguration.setMaxAge(MAX_AGE);
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", corsConfiguration); // 4、对接口配置跨域设置
        return new CorsFilter(source);
    }
}

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值