vue + springboot 前后端分离,跨域问题

本文介绍了解决Vue+SpringBoot项目中跨域问题的三种方法,包括全局配置、过滤器及控制器注解,适用于本地开发环境。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

vue + springboot 前后端分离,遇到的第一个坑就是:跨域问题

本地开发,都是localhost,但是由于端口不同,导致出现跨域问题。

网上搜索,解决方法(三种,尝试了后两种,亲测,都可以解决):

第一种方式:

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("*")
                .allowedMethods("GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS")
                .allowCredentials(true)
                .maxAge(3600)
                .allowedHeaders("*");
    }
}

这种方式是全局配置的,网上也大都是这种解决办法,但是很多都是基于旧的spring版本,比如:

Spring Boot如何解决前端的Access-Control-Allow-Origin跨域问题

文中WebMvcConfigurerAdapter在spring5.0已经被标记为Deprecated,点开源码可以看到:

/**
 * An implementation of {@link WebMvcConfigurer} with empty methods allowing
 * subclasses to override only the methods they're interested in.
 *
 * @author Rossen Stoyanchev
 * @since 3.1
 * @deprecated as of 5.0 {@link WebMvcConfigurer} has default methods (made
 * possible by a Java 8 baseline) and can be implemented directly without the
 * need for this adapter
 */
@Deprecated
public abstract class WebMvcConfigurerAdapter implements WebMvcConfigurer {}

像这种过时的类或者方法,spring的作者们一定会在注解上面说明原因,并告诉你新的该用哪个,这是非常优秀的编码习惯,点赞!

spring5最低支持到jdk1.8,所以注释中明确表明,你可以直接实现WebMvcConfigurer接口,无需再用这个适配器,因为jdk1.8支持接口中存在default-method。

该方式未测试

第二种方式:

import org.springframework.context.annotation.Configuration;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(filterName = "CorsFilter ")
@Configuration
public class CorsFilter implements Filter {
    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) res;
        response.setHeader("Access-Control-Allow-Origin","*");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, PATCH, DELETE, PUT");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
        chain.doFilter(req, res);
    }
}

第三种方式:

@Slf4j
@RestController
public class loginController {

    @CrossOrigin(allowCredentials = "true",allowedHeaders = "*")
    @RequestMapping(value = "/api/login",method = RequestMethod.POST)
    public String login(){
        log.info("**************身份验证****************");
        return "success";
    }

}

使用@CrossOrigin标签,并同时设置请求方法 POST / GET 。

参数:allowCredentials为true时,返回的响应头AccessControlAllowCredentials属性才设置为true,允许客户端携带验证消息。

    allowedHeaders = "*"表示允许所有请求头通过。

在使用第三种方式时,提示jdk版本过低,需更改jdk版本1.8.

参考:https://segmentfault.com/a/1190000019550329?utm_source=tag-newest

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值