Skip to content
The Chat Archive
gpt-4-0314· OpenAI WildChat-4.8M (AI2)

springboot 处理vue前端访问跨域问题

  1. User

    springboot 处理vue前端访问跨域问题

  2. Assistant

    在使用 Vue 前端框架与 Spring Boot 后端框架进行交互时,通常会出现跨域问题。要解决这个问题,需要对 Spring Boot 进行一些配置。以下是解决方法:

    1. 方法一:通过 @CrossOrigin 注解解决跨域问题

    在 Spring Boot 控制器的请求映射方法上添加 @CrossOrigin 注解,这样就可以允许指定来源的跨域访问。

    import org.springframework.web.bind.annotation.CrossOrigin;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    @RestController
    public class TestController {
    
        @CrossOrigin(origins = "http://localhost:8080") // 允许该域名下的请求跨域访问
        @GetMapping("/test")
        public String test() {
            return "Hello, Vue!";
        }
    }
    
    1. 方法二:通过全局配置解决跨域问题

    创建一个配置类 WebConfig,并实现 WebMvcConfigurer 接口。在 addCorsMappings 方法中配置跨域设置。

    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 WebConfig implements WebMvcConfigurer {
    
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/**") // 针对所有请求进行跨域配置
                    .allowedOrigins("http://localhost:8080") // 指定允许跨域访问的域名
                    .allowedMethods("*") // 允许任何请求方法(GET、POST等)
                    .allowedHeaders("*") // 允许任何请求头
                    .allowCredentials(true) // 允许携带身份认证信息(如 cookie)
                    .maxAge(3600); // 跨域请求的有效时间(单位:秒)
        }
    }
    

    使用这两种方法中的任意一种,都可以解决 Vue 前端与 Spring Boot 后端交互时的跨域问题。