zoukankan      html  css  js  c++  java
  • Spring Boot跨域解决方案

    一、什么是跨域

    为保证浏览器的安全,不同源的客户端脚本在没有明确授权的情况下,不能读写对方资源,这称之为同源策略,如果一个请求地址里的协议、域名、端口号都相同,就属于同源。依据浏览器同源策略,非同源脚本不可操作其他源下的对象,想要操作其他源下的对象就需要跨域。

    二、CORS

    CORS是为解决浏览器跨域问题由W3C提出的跨源资源共享方案,CORS可以在不破坏即有规则的情况下,通过后端服务器实现CORS接口,从而实现跨域通信。

    三、实现

    • config包下添加CORS配置类,实现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("*")	// 允许跨域访问的源
            .allowedMethods("POST", "GET", "PUT", "OPTIONS", "DELETE")	// 允许请求方法
            .maxAge(168000)	// 预检间隔时间
            .allowedHeaders("*")  // 允许头部设置
            .allowCredentials(true);	// 是否发送cookie
        }
    }
    

    这样,每当客户端发送请求时,都会在头部附上跨域信息,就可以支持跨域访问了

  • 相关阅读:
    实操ES6之Promise
    RabbitMQ入门指南
    【从零开始撸一个App】PKCE
    SpringCloud Alibaba Nacos Config 配置中心
    SpringCloud Alibaba Nacos 服务发现 Feign进行消费
    SpringCloud Alibaba Nacos 服务发现 RestTemplate进行消费
    SpringCloud Alibaba Nacos 服务注册
    SpringCloud Alibaba Nacos 服务治理中心
    开发者-管理者 设计陷阱
    java8中的Stream API实战
  • 原文地址:https://www.cnblogs.com/maggieq8324/p/11414666.html
Copyright © 2011-2022 走看看