解决前后端交互中出现的跨域问题(基于Springboot和Vue3)
一、问题描述

二、问题解决
在 Spring Boot 项目的 Java 代码中,创建一个配置类来处理 CORS。例如,在config
包下创建CorsConfig.java
文件,内容如下:
2.1允许所有地址访问的情形
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() {
CorsConfiguration config = new CorsConfiguration();
// 允许所有来源,生产环境建议指定前端具体域名,如 config.addAllowedOrigin("http://localhost:8089");
config.addAllowedOrigin("*");
config.addAllowedMethod("*"); // 允许所有HTTP方法,如GET、POST、PUT、DELETE等
config.addAllowedHeader("*"); // 允许所有请求头
config.setAllowCredentials(true); // 允许携带凭证,如cookie
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", config); // 对所有接口生效,也可指定特定路径,如"/api/**"
return new CorsFilter(source);
}
}
2.2允许指定地址访问的情形
package com.hechixueyuan.Student_Mannage_System_h.config;
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("/**")
.allowedOrigins("http://localhost:8089") // 允许的前端地址
// .allowedOrigins("*") // 允许的前端地址
.allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
.allowedHeaders("*")
.allowCredentials(true)
.maxAge(3600); // 预检请求缓存时间
}
}
注意“.allowedOrigins(“*”) (表示 允许的前端地址)“,与“ .allowCredentials(true)(表示允许携带凭证(如Cookie))”是不能同时出现的,这在 CORS 规范中是冲突的。
(如果报的是axios或者element-plus的问题可以试图清除缓存,重新加载依赖,同时注意在man.js文件中配置相关的包等。)