SpringBoot 三步骤轻松解决跨域

1、添加maven依赖注解

       <!--跨域需要的jar包-->
        <dependency>
            <groupId>com.thetransactioncompany</groupId>
            <artifactId>java-property-utils</artifactId>
            <version>1.9.1</version>
        </dependency>
        <dependency>
            <groupId>com.thetransactioncompany</groupId>
            <artifactId>cors-filter</artifactId>
            <version>2.5</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
            <scope>provided</scope>
        </dependency>

2、添加跨域请求配置类CorsConfig

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 {
    private CorsConfiguration buildConfig() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedOrigin("*"); // 1
        corsConfiguration.addAllowedHeader("*"); // 2
        corsConfiguration.addAllowedMethod("*"); // 3
        return corsConfiguration;
    }

    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", buildConfig()); // 4
        return new CorsFilter(source);
    }
}

3、在接收到OPTIONS请求时候,需要返回状态码为202,并且设置响应头部(根据需求变更)

HttpServletResponse httpResponse = response;
        httpResponse.setCharacterEncoding("UTF-8");
        httpResponse.setContentType("application/json; charset=utf-8");
        httpResponse.setHeader("Access-Control-Allow-Origin","*");
        httpResponse.setHeader("Access-Control-Allow-Credentials", "true");
        httpResponse.setHeader("Access-Control-Allow-Methods", "POST,GET,OPTIONS,DELETE,PATCH,PUT");
        httpResponse.setHeader("Access-Control-Max-Age", "3600");
        httpResponse.setHeader("Access-Control-Allow-Headers", "Origin,X-Requested-With,x-requested-with,X-Custom-Header," +
                "Content-Type,Accept,Authorization");
        String method = request.getMethod();
        if ("OPTIONS".equalsIgnoreCase(method)){
            logger.info("OPTIONS请求");
            httpResponse.setStatus(HttpServletResponse.SC_ACCEPTED);
        }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
跨域问题是由于浏览器的同源策略所导致的,为了保障网站的安全,浏览器只允许相同协议、域名、端口号的请求访问。因此在开发中,如果前端项目(Vue)和后端项目(Spring Boot)不在同一个域名下,就会出现跨域问题。 解决跨域问题有多种方法,以下是其中两种比较常用的方式: 1. 使用Spring Boot的CORS支持 Spring Boot提供了跨域资源共享(CORS)的支持。可以通过在后端代码中配置跨域访问的规则,告诉浏览器允许哪些域名访问后端接口。具体操作为在Spring Boot的配置文件中添加如下配置: ``` # 允许所有的域名都可以跨域访问本站的所有资源 # 当需要限制某个域名访问时,只需要修改 allowedOrigins 的值即可 spring: cors: allowed-origins: "*" allowed-methods: GET, POST, PUT, DELETE allowed-headers: "*" ``` 2. 使用Vue的代理 在开发环境中,可以在Vue的配置文件中添加代理来解决跨域问题。具体操作为在Vue的配置文件中添加如下配置: ``` module.exports = { devServer: { proxy: { '/api': { target: 'http://localhost:8080', // 后端接口地址 changeOrigin: true, // 是否允许跨域 pathRewrite: { '^/api': '' // 重写接口 } } } } } ``` 上述代码中,我们在Vue的配置文件中通过proxy属性配置了一个代理,将所有以/api开头的请求都转发到http://localhost:8080上,并开启了跨域支持。需要注意的是,由于后端接口的地址不一定是localhost:8080,具体地址需要根据实际情况进行修改。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值