springboot后台跨域设置

版权声明:未经授权,不得转载。 https://blog.csdn.net/soulsda/article/details/84280700

1.跨域

   跨域什么的没什么好讲的,我也不大清楚,大概是请求返回过去的地址、ip、端口之类的和请求来的地方不同,就会获取不到信息,总之前端后台都有解决方案,我这里讲一下后台 和 前端的json传输

2.具体代码

    2.1:基于mvc 4.3.8 版本 

             

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;


@Configuration
public class MyCorsConfig extends WebMvcConfigurerAdapter{


    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowCredentials(true)
                .allowedMethods("GET","POST","DELETE","PUT")
                .maxAge(3600);
    }


}

     2.2:基于mvc 5.0.7 (听说现在用spring5.x 开发的 上线前都要请道士做法保佑 -_-||)

             


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


@Configuration
public class MyCorsConfig implements WebMvcConfigurer {


    @Bean
    public CorsFilter corsFilter() {
        final UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();
        final CorsConfiguration corsConfiguration = new CorsConfiguration();
        //验证信息权限
        corsConfiguration.setAllowCredentials(true);
        //域名访问权限
        corsConfiguration.addAllowedOrigin("*");
        //请求头访问权限
        corsConfiguration.addAllowedHeader("*");
        //get post权限
        corsConfiguration.addAllowedMethod("*");
        //所有url都可以访问
        urlBasedCorsConfigurationSource.registerCorsConfiguration("/**", corsConfiguration);
        return new CorsFilter(urlBasedCorsConfigurationSource);
    }


}

3.用法

    类似拦截器吧,感觉,直接放到和controller层同一个工程里面,同不同文件夹无所谓,最后打包在同一个jar包里面就行。

4.缺点

    也不算缺点就是有种情况仍然不可以使用,就是用json传输时,无论怎么样都会出现跨域问题,试过注解 @CrossOrigin 直接加载方法上也不行,后来明白似乎不是后台的锅,查找了很多文档,发现似乎需要改前端的请求方式。

     把请求头中的Content-Type的
     application/x-www-form-urlencoded
     切换为text/plain

     我不太懂这些,也不知道为什么,反正可以用就行,毕竟我只是后台开发。

5.闲谈

   写到这里我有点想去学下通信协议,类似http、rpc之类的东西,感觉很有意思。

猜你喜欢

转载自blog.csdn.net/soulsda/article/details/84280700