zoukankan      html  css  js  c++  java
  • SpringBoot 解决跨域

    第一种办法:

    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("*");
        }
    }

    第二种办法:

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

    第三种办法:

    public class GoodsController {
        @CrossOrigin(origins = "http://localhost:4000")
        @GetMapping("goods-url")
        public Response queryGoodsWithGoodsUrl(@RequestParam String goodsUrl) throws Exception {}
    }

    没错就是 @CrossOrigin 注解,点开注解

    @Target({ ElementType.METHOD, ElementType.TYPE })
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    public @interface CrossOrigin {}

    https://mp.weixin.qq.com/s/L6Pc4P3ceLf4Chy2bKl6Hg

    故乡明
  • 相关阅读:
    kolla
    lbaas
    celery
    redis发布订阅
    数据库简单介绍
    celery
    ansible初识
    315
    request
    navicat连接mysql报错1251解决方案
  • 原文地址:https://www.cnblogs.com/luweiweicode/p/15124146.html
Copyright © 2011-2022 走看看