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

  • 相关阅读:
    安卓 广播机制
    安卓 活动的启动模式
    安卓 生命周期
    安卓六大布局
    day4-list,列表
    Leetcode 947 移除最多的同行或同列石头
    Leetcode 628三个数的最大乘积
    Leetcode 1584连接所有点的最小费用
    Leetcode 721 账户合并
    Leetcode 103 二叉树的锯齿层序遍历
  • 原文地址:https://www.cnblogs.com/xiang--liu/p/9710217.html
Copyright © 2011-2022 走看看