栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

SpringBoot 跨域解决方案

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

SpringBoot 跨域解决方案

什么是跨域?       

 跨域资源共享(CORS) 是一种机制,它使用额外的 HTTP 头来告诉浏览器 让运行在一个 origin (domain) 上的Web应用被准许访问来自不同源服务器上的指定的资源。当一个资源从与该资源本身所在的服务器不同的域、协议或端口请求一个资源时,资源会发起一个跨域 HTTP 请求。

比如:http://cyun.top

http://cyun.top/home  不跨域

http://cyun.top:8080  跨域 端口不同

https://cyun.top  跨域   协议不同

http://admin.cyun.top   跨域   域名不同

常见跨域解决几种方式

1、使用@CrossOrigin

a.方法上加

@CrossOrigin(origins = "*") 

@PostMapping("/login") 

public String login(@RequestBody User user){

        return "";

}

b.类上加(origin="*" 代表所有域名都可访问  maxAge表示cookie的有效期 单位为秒)

@CrossOrigin(origins = "*",maxAge = 1800)

public class UserController {

}

2、使用WebMvcConfigurer 配置

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 CorsConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
            .allowedOrigins("*")
            .allowCredentials(true)
            .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
            .maxAge(1800);
    }
}

3、使用CorsFilter

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;
@Configuration
public class CorsConfig {
    @Bean
    public CorsFilter corsFilter(){
        CorsConfiguration config = new CorsConfiguration();
        config.addAllowedHeader("*");
        config.addAllowedMethod("*");
        config.addAllowedOrigin("*");
        config.setAllowCredentials(true);
        UrlbasedCorsConfigurationSource configSource = new UrlbasedCorsConfigurationSource();
        configSource.registerCorsConfiguration("/**", config);
        return new CorsFilter(configSource);
    }
}

4、网关配置(springcloud)

spring:
  application:
    name: gateway-service
  profiles:
    active: default

  cloud:
    gateway:
      globalcors:
        cors-configurations:
          '[/**]':
              allowedOrigins: "*"   #跨域处理运行所有跨域
              allowedMethods:        #支持方法
                -GET
                -POST
                -PUT
                -DELETE
              allowedHeaders: "*"
              allowCredentials: true

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/318014.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号