Springboot解决Access-Control-Allow-Origin跨域问题

最近在开发过程中遇到Access-Control-Allow-Origin这个问题,下面是个人网上搜罗的方法


前言

这个方法适用于springboot


提示:以下是本篇文章正文内容,下面案例可供参考

一、添加配置文件

springboot的配置文件里添加,允许同一个局域网下的人访问

#配置同一个局域网访问
server.address=0.0.0.0

二,创建文件

1.创建CorsFilter类

代码如下(示例):

import org.springframework.stereotype.Component;

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

/**
 * @description:过滤器
 * @author: GavenLee
 * @time: 2020/10/20 9:53
 */
@Component
@WebFilter(urlPatterns = "/*", filterName = "CorsFilter")
public class CorsFilter implements Filter {

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) res;
        HttpServletRequest reqs = (HttpServletRequest) req;
        String curOrigin = reqs.getHeader("Origin");
        response.setHeader("Access-Control-Allow-Origin", curOrigin == null ? "true" : curOrigin);
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, PATCH, DELETE, PUT");
        response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
        chain.doFilter(req, res);
    }


    @Override
    public void init(FilterConfig filterConfig) {
        System.out.println("=======================================================出来了=================================================");
    }

    @Override
    public void destroy() {}

}

2.创建CorsConfig类

代码如下(示例):

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

/**
 * @description:跨域请求配置
 * @author: GavenLee
 * @time: 2020/10/20 9:55
 */
@Configuration
public class CorsConfig  extends WebMvcConfigurerAdapter {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**").allowedOrigins("*")
                .allowedMethods("GET", "HEAD", "POST","PUT", "DELETE", "OPTIONS")
                .allowCredentials(true).maxAge(3600);
    }

}

重启项目ok


©️2020 CSDN 皮肤主题: 数字20 设计师:CSDN官方博客 返回首页