springboot+vue项目中,加上这个跨域请求拦截就会无法登录,应该怎么解决
2条回答 默认 最新
关注 引自免费微信小程序:皆我百晓生
针对你描述的问题,Spring Boot + Vue 项目在添加了跨域请求拦截配置后无法登录的情况,我们可以从几个角度来分析并解决这个问题。
首先,检查你的跨域配置代码中有一些小错误,例如
addALLowedOrigin
应为allowedOrigin
,但实际的正确写法是allowOrigins
。此外,registerCorsConfiguration
方法的参数中的path
是一个错误的键名,正确的应该是使用UrlPathHelper
的默认路径匹配器,无需额外指定路径键。以下是修正后的代码示例:@Bean public CorsFilter corsFilter() { CorsConfiguration corsConfiguration = new CorsConfiguration(); corsConfiguration.addAllowedOrigin("http://localhost:80"); corsConfiguration.addAllowedHeader("*"); corsConfiguration.addAllowedMethod("*"); corsConfiguration.setAllowCredentials(true); UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**", corsConfiguration); return new CorsFilter(source); }
但是,这里有一个更简洁的写法,使用 Spring Boot 的自动配置特性,可以将上述代码简化为:
@Configuration @EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.cors().and().csrf().disable(); } @Bean public CorsConfigurationSource corsConfigurationSource() { CorsConfiguration configuration = new CorsConfiguration(); configuration.addAllowedOrigin("http://localhost:80"); configuration.addAllowedHeader("*"); configuration.addAllowedMethod("*"); configuration.setAllowCredentials(true); UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**", configuration); return source; } }
接下来,确保你的前端 Vue 应用正在向正确的后端 URL 发送请求。在开发环境中,Vue 通常运行在
http://localhost:8080
或其他端口上,而你的跨域配置中只允许了http://localhost:80
的请求。因此,你需要确认前端发送请求的 URL 是否与你配置的允许访问的 URL 匹配。最后,检查你的 Spring Security 配置是否可能阻止了登录请求。如果你有安全相关的配置,例如 CSRF 保护或其他身份验证过滤器,它们可能会干扰到跨域请求的处理。确保你的安全配置允许预检请求(OPTIONS 方法),并正确处理 CORS 凭证。
如果以上步骤都无法解决问题,建议检查服务器的日志输出,以获取更多关于 403 错误的具体原因的信息。这将有助于进一步定位问题所在。
解决 无用评论 打赏 举报 编辑记录
悬赏问题
- ¥15 单纯型python实现编译报错
- ¥15 c++2013读写oracle
- ¥15 c++ gmssl sm2验签demo
- ¥15 关于模的完全剩余系(关键词-数学方法)
- ¥15 有没有人懂这个博图程序怎么写,还要跟SFB连接,真的不会,求帮助
- ¥15 PVE8.2.7无法成功使用a5000的vGPU,什么原因
- ¥15 is not in the mmseg::model registry。报错,模型注册表找不到自定义模块。
- ¥15 安装quartus II18.1时弹出此error,怎么解决?
- ¥15 keil官网下载psn序列号在哪
- ¥15 想用adb命令做一个通话软件,播放录音