zoukankan      html  css  js  c++  java
  • spring boot配置跨域

    在前后端分离的趋势下,前端和后端的交互难免会出现跨域的情况,配置跨域有很多种方法:

    1、使用spring boot配置跨域

      a. 定义一个配置类,实现 WebMvcConfigurer 接口,这个接口可配置拦截器、参数解析器、返回值解析器、跨域支持等等

    package io.xiongdi.config;
    
    import io.xiongdi.interceptor.AuthorizationInterceptor;
    import io.xiongdi.resolver.LoginUserHandlerMethodArgumentResolver;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.web.method.support.HandlerMethodArgumentResolver;
    import org.springframework.web.servlet.config.annotation.CorsRegistry;
    import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
    import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
    
    import java.util.List;
    
    /**
     * @author wujiaxing
     * <p>
     *     此配置类可配置拦截器、参数解析器、返回值解析器、跨域支持等等
     * </p>
     */
    @Configuration
    public class WebMvcConfig implements WebMvcConfigurer {
    
        @Autowired
        private AuthorizationInterceptor authorizationInterceptor;
        @Autowired
        private LoginUserHandlerMethodArgumentResolver loginUserHandlerMethodArgumentResolver;
    
        /**
         * 拦截器配置
         * @param registry
         */
        @Override
        public void addInterceptors(InterceptorRegistry registry) {
            registry.addInterceptor(authorizationInterceptor).addPathPatterns("/api/**");
        }
    
        /**
         * 跨域支持配置
         * @param registry
         */
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/**").allowCredentials(true).allowedOrigins("*").allowedMethods("GET", "PUT", "DELETE", "POST", "OPTIONS").maxAge(3600);
        }
    
        /**
         * 参数解析配置
         * @param resolvers
         */
        @Override
        public void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) {
            resolvers.add(loginUserHandlerMethodArgumentResolver);
        }
    }

      b. 简单的配置就支持跨域了,要注意匹配路径,我写成 /* 就不行,/** 就可以

    只要你不觉得尴尬,那尴尬的就是别人
  • 相关阅读:
    ES基本介绍
    Mybatis 读写分离简单实现
    分享一个Flink checkpoint失败的问题和解决办法
    一次“内存泄露”引发的血案
    记一次堆外内存泄漏排查过程
    MySQL主从复制读写分离,看这篇就够了!
    JVM运行时内存数据区域
    .NET MVC 页面传值方式
    jQuery 对表格内容进行搜索筛选
    泛型
  • 原文地址:https://www.cnblogs.com/wujiaxing/p/11179930.html
Copyright © 2011-2022 走看看