vue跨域java类

package com.example.springboot.utils;

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);
    }
}

自己复制在自己的工具类中就可以

也是在别人地方找到的

### Spring Boot 与 Vue 配置导致 500 错误的解决方案 当遇到 Spring Boot 和 Vue 项目之间因问题引发的 500 错误时,通常是因为服务器端未能正确处理来自客户端的请求头或响应头。以下是详细的分析和解决方法: #### 1. **全局 CORS 配置** 可以通过创建一个自定义的 `WebMvcConfigurer` 来实现全局的支持。这种方式适用于大多数场景。 ```java @Configuration public class CorsConfig implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") // 所有路径均允许访问 .allowedOrigins("http://localhost:8080") // 允许特定名访问 .allowCredentials(true) // 是否支持携带 Cookie 凭证 .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS") // 允许的方法.maxAge(3600); // 预检请求的有效期(秒) } } ``` 此配置解决了 `allowCredentials` 和 `allowedOrigins` 使用 `"*"` 的冲突问题[^1]。 --- #### 2. **局部 CORS 配置** 如果只需要针对某些接口启用支持,则可以在控制器上使用 `@CrossOrigin` 注解。 ```java @RestController @RequestMapping("/api") @CrossOrigin(origins = "http://localhost:8080", allowCredentials = "true") public class MyController { @GetMapping("/data") public String getData() { return "Data fetched successfully!"; } } ``` 这种方法适合于仅需部分接口开放的情况[^3]。 --- #### 3. **前端 Axios 请求前缀配置** 为了确保所有对后端的请求都通过 `/api` 前缀发送,在 Vue 项目的 `axios` 实例中统一设置基础 URL。 ```javascript import axios from 'axios'; const instance = axios.create({ baseURL: '/api', // 统一的基础URL timeout: 1000, }); export default instance; ``` 这样可以减少手动拼接 URL 的复杂度,并使代码更加清晰。 --- #### 4. **检查预检请求 (Preflight Request)** 浏览器在发起实际请求之前会先发出 OPTIONS 型的预检请求,以确认目标资源是否能够接受该请求。因此需要确保服务器端能正常响应此请求。 ```java @Override public void configure(HttpSecurity http) throws Exception { http.cors().and() .csrf().disable(); // 如果不需要 CSRF 功能可禁用 } @Bean public CorsConfigurationSource corsConfigurationSource() { CorsConfiguration configuration = new CorsConfiguration(); configuration.setAllowedOrigins(Collections.singletonList("http://localhost:8080")); configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS")); configuration.setAllowCredentials(true); configuration.setAllowedHeaders(Arrays.asList("*")); UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**", configuration); return source; } ``` 这一步对于复杂的需求尤为重要[^4]。 --- #### 5. **Token 拦截器中的处理** 如果有 Token 校验机制,可能因为未正确传递凭证而导致 500 错误。此时可在拦截器中加入额外逻辑来验证并放行合法请求。 ```java @Component public class LoginInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { String token = request.getHeader("Authorization"); if ("OPTIONS".equals(request.getMethod())) { // 处理预检请求 response.setStatus(HttpServletResponse.SC_OK); return true; } if (!StringUtils.isEmpty(token)) { try { JwtUtil.parseJWT(token); // 自定义解析工具 return true; } catch (Exception e) { throw new RuntimeException("Invalid token"); } } else { throw new RuntimeException("No token provided"); } } } ``` 这种设计避免了由于权限校验失败而触发的服务端异常[^5]。 --- ### 总结 综合来看,造成 500 错误的原因可能是多方面的,包括但不限于 CORS 配置不当、预检请求未被妥善处理或者认证流程存在漏洞等问题。按照上述建议逐一排查即可有效解决问题。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值