zoukankan      html  css  js  c++  java
  • web开发-CORS支持

    一、简介

    Web 开发经常会遇到跨域问题,解决方案有:jsonp,iframe,CORS 等等

    1.1、CORS与JSONP相比

    1、JSONP只能实现GET请求,而CORS支持所有类型的HTTP请求。

    2、使用CORS,开发者可以使用普通的XMLHttpRequest发起请求和获得数据,比起JSONP 有更好的错误处理。

    3、JSONP主要被老的浏览器支持,它们往往不支持CORS,而绝大多数现代浏览器都已经支持了CORS浏览器支持情况

      Chrome 3+

      Firefox 3.5+

      Opera 12+

      Safari 4+

      Internet Explorer 8+

    二、实现CORS

    说明:在springMVC中可以配置全局的规则,也可以使用@CrossOrigin注解进行细粒度的配置

    2.1、全局配置

    方式一:注册bean

    package com.example.demo.utils.configuration;
    
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.web.servlet.config.annotation.CorsRegistry;
    import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
    import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
    
    /**
     * Created by DELL on 2017/6/18.
     */
    @Configuration
    public class CustomCorsConfiguration {
        @Bean
        public WebMvcConfigurer corsConfigurer() {
            return new WebMvcConfigurerAdapter() {
                @Override
                public void addCorsMappings(CorsRegistry registry) {
                    registry.addMapping("/api/**").allowedOrigins("http://localhost:8080");
                }
            };
        }
    }

    说明:表示对于/api请求下的所以资源,允许http://localhost:8080访问

    方式二:继承WebMvcConfigurerAdapter

    package com.example.demo.utils.configuration;
    
    import org.springframework.web.servlet.config.annotation.CorsRegistry;
    import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
    
    /**
     * 跨域请求处理
     * @Author: 我爱大金子
     * @Description: 跨域请求处理
     * @Date: Created in 10:12 2017/6/18
     */
    @Configuration
    public class CustomCorsConfiguration2 extends WebMvcConfigurerAdapter {
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/api/**").allowedOrigins("http://localhost:8080");
        }
    }

    说明:表示对于/api请求下的所以资源,允许http://localhost:8080访问

    2.2、细粒度配置

    在controller中加入@CrossOrigin注解,如:@CrossOrigin(origins = "http://localhost:8080")

    技术分享

    本文出自 “我爱大金子” 博客,请务必保留此出处http://1754966750.blog.51cto.com/7455444/1939451

    springBoot(9):web开发-CORS支持

    标签:springboot   springboot web开发-cors支持   

    原文地址:http://1754966750.blog.51cto.com/7455444/1939451

  • 相关阅读:
    《重构》读书笔记
    每周总结
    《修改代码的艺术》读书笔记
    每周总结
    每周总结
    《修改代码的艺术》读书笔记
    每周总结
    第二周周总结
    以淘宝网为例,描绘质量属性的六个常见属性场景
    机器学习第八讲
  • 原文地址:https://www.cnblogs.com/xiang--liu/p/9710217.html
Copyright © 2011-2022 走看看