问小白 wenxiaobai
资讯
历史
科技
环境与自然
成长
游戏
财经
文学与艺术
美食
健康
家居
文化
情感
汽车
三农
军事
旅行
运动
教育
生活
星座命理

Vue项目axios请求Spring Boot接口时的CORS跨域问题解决方案

创作时间:
作者:
@小白创作中心

Vue项目axios请求Spring Boot接口时的CORS跨域问题解决方案

引用
CSDN
1.
https://blog.csdn.net/HQC66666/article/details/139114330

在前端开发中,跨域问题是一个常见的困扰。当你使用Vue项目通过axios请求后端Spring Boot接口时,可能会遇到以下错误:

Access to XMLHttpRequest at 'http://localhost:8888/user/selectAll' from origin 'http://localhost:9999' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

这个错误是由于浏览器的同源策略(Same-origin policy)限制了一个源(域名、协议、端口)的文档或脚本如何与另一个源的资源进行交互。这是一种安全机制,用于限制恶意网站访问另一个源下的敏感信息。

解决办法1:在Spring后端使用注解@CrossOrigin

你可以在数据访问层使用此注解,如下图:

解决办法2:在Spring后端创建全局配置类

你也可以创建一个全局配置类来解决跨域问题:

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 {
    // 当前跨域请求最大有效时长。这里默认1天
    private static final long MAX_AGE = 24 * 60 * 60;
    
    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedOrigin("*"); // 1 设置访问源地址
        corsConfiguration.addAllowedHeader("*"); // 2 设置访问源请求头
        corsConfiguration.addAllowedMethod("*"); // 3 设置访问源请求方法
        corsConfiguration.setMaxAge(MAX_AGE);
        source.registerCorsConfiguration("/**", corsConfiguration); // 4 对接口配置跨域设置
        return new CorsFilter(source);
    }
}

通过以上两种方式,你可以轻松解决Vue项目通过axios请求Spring Boot接口时遇到的CORS跨域问题。

© 2023 北京元石科技有限公司 ◎ 京公网安备 11010802042949号