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

posted @ 2019-07-13 11:34  渣男梦想  阅读(547)  评论(0编辑  收藏  举报