SpringBoot2.x前后端分離跨域問題及Swagger不能訪問


一、只需在添加一下配置,即可解決

package com.liangjian.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.*;

/**
 * 解決跨域訪問
 */

@Configuration
public class WebConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        //設置允許跨域的路徑
        registry.addMapping("/**")
                //設置允許跨域請求的域名
                .allowedOrigins("*")
                //是否允許證書 不再默認開啟
                .allowCredentials(true)
                //設置允許的方法
                .allowedMethods("*")
                //跨域允許時間
                .maxAge(3600);
    }

    /**
     * 跨域配置后swagger2可能不能訪問,需要增加如下配置
     * @param registry
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("swagger-ui.html")
                .addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");
        
    }

    
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM