只通过springboot一键解决跨域问题

只通过springboot一键解决跨域问题

本文讲解如何只通过springboot就可以解决跨域问题。
只需要添加CorsConfig这个类就可以了

package com.example.examandquestion.config;


import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.cors.CorsConfiguration;

@Configuration
public class CorsConfig {
    
    
  @Bean
  public CorsFilter corsFilter() {
    
    
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    CorsConfiguration config = new CorsConfiguration();
    config.addAllowedOrigin("http://localhost:8080");
    config.addAllowedHeader("*");
    config.addAllowedMethod("*");
    config.setAllowCredentials(true);
    source.registerCorsConfiguration("/**", config);
    return new CorsFilter(source);
  }
}

在这里插入图片描述
然后对于前端就不存在跨域问题了。
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_51447496/article/details/131143780
今日推荐