SpringBoot 允許跨域配置

邢闖洋發表於2022-03-08

之前的介面一直都是 App 客戶端呼叫,不存在跨域問題。

這次是介面需要讓 web 端呼叫,遇到了跨域問題。

解決只需要在 SpringBoot 中新增一個配置類即可。

package com.sktk.question.config;

import org.springframework.beans.factory.annotation.Configurable;
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 CrossConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowedMethods("GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS")
                .allowCredentials(true)
                .maxAge(3600)
                .allowedHeaders("*");
    }
}

參考文章

springboot允許跨域訪問

本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章