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. 简单的配置就支持跨域了,要注意匹配路径,我写成 /* 就不行,/** 就可以

    只要你不觉得尴尬,那尴尬的就是别人
  • 相关阅读:
    UOJ #455 [UER #8]雪灾与外卖 (贪心、模拟费用流)
    Codeforces 482E ELCA (LCT)
    Codeforces 798D Mike and distribution (构造)
    AtCoder AGC017C Snuke and Spells
    HDU 6089 Rikka with Terrorist (线段树)
    HDU 6136 Death Podracing (堆)
    AtCoder AGC032D Rotation Sort (DP)
    jenkins+python+kubectl实现批量更新k8s镜像
    Linux 下载最新kubectl版本的命令:
    jenkins X 和k8s CI/CD
  • 原文地址:https://www.cnblogs.com/wujiaxing/p/11179930.html
Copyright © 2011-2022 走看看