两种方法从SpringBoot的方向解决跨域问题

今天搭建博客的时候,尝试性的传递数据,发现浏览器报了这个错误

…blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource. If an opaque response serves your needs, set the request’s mode to ‘no-cors’ to fetch the resource with CORS disabled.

也就是跨域请求的错误

首先 在运行过程中,通过各种测试,发现前端的设置并不影响跨域,只要后端配置了允许跨域就能进行跨域请求

解决跨域,SpringBoot2.x版本

这次知道了有些问题,直接在Spring官网搜索,好像要方便些

Spring官方关于配置跨域的引导

SpringBoot2.x版本对跨域的支持有了更好的完善

参考文档我们能知道两种方法设置跨域

  1. Controller method CORS configuration(基于Controller的跨域配置)
  2. Global CORS configuration(全局跨域配置)

基于Controller的跨域配置

使用@CrossOrigin注解,我们先码一下官方介绍

  @CrossOrigin(origins = "http://localhost:9000")
@GetMapping("/greeting")
public Greeting greeting(@RequestParam(required=false, defaultValue="World") String name) {
System.out.println("==== in greeting ====");
return new Greeting(counter.incrementAndGet(), String.format(template, name));
}

This @CrossOrigin annotation enables cross-origin requests only for this specific method.

By default, its allows all origins, all headers, the HTTP methods specified in the @RequestMapping annotation and a maxAge of 30 minutes is used. You can customize this behavior by specifying the value of one of the annotation attributes: origins, methods, allowedHeaders, exposedHeaders, allowCredentials or maxAge. In this example, we only allow http://localhost:9000 to send cross-origin requests.

上面叽叽喳喳大致意思是,用@CrossOrigin注解在@Controller类上就能打开跨域,默认允许所有的访问,如果要定制的话,加属性即可,有

  1. origins(允许跨域请求的域名),
  2. methods(方法),
  3. allowedHeaders
  4. exposedHeaders
  5. allowCredentials
  6. maxAge(跨域允许的时间)

全局跨域配置

全局跨域配置使用的是SpringBoot的配置,重写WebMvcConfiger中的addCorsMappings方法,用Bean的方法注入即可达到开启多个跨域的效果,更多的配置,类似上面的6条,直接添加即可

下面是原文:

As an alternative to fine-grained annotation-based configuration, you can also define some global CORS configuration as well. This is similar to using a Filter based solution, but can be declared within Spring MVC and combined with fine-grained @CrossOrigin configuration. By default all origins and GET, HEAD and POST methods are allowed.

src/main/java/hello/GreetingController.java

  @GetMapping("/greeting-javaconfig")
public Greeting greetingWithJavaconfig(@RequestParam(required=false, defaultValue="World") String name) {
System.out.println("==== in greeting ====");
return new Greeting(counter.incrementAndGet(), String.format(template, name));
}
src/main/java/hello/Application.java
  @Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/greeting-javaconfig")
.allowedOrigins("http://localhost:9000");
}
};
}

You can easily change any properties (like the allowedOrigins one in the example), as well as only apply this CORS configuration to a specific path pattern. Global and controller level CORS configurations can also be combined.

除了上面这种添加Bean的配置方式,我们也可以用实现接口的方法来实现

@Configuration
@EnableWebMvc
public class CorsConfig implements WebMvcConfigurer { @Override
public void addCorsMappings(CorsRegistry registry) {
//设置允许跨域的路径
registry.addMapping("/**")
//设置允许跨域请求的域名
.allowedOrigins("*")
//是否允许证书 不再默认开启
.allowCredentials(true)
//设置允许的方法
.allowedMethods("*")
//跨域允许时间
.maxAge(3600);
}
}

效果是相同的,完全可行

Fetch+SpringBoot跨域请求设置的更多相关文章

  1. springboot跨域请求设置

    当它请求的一个资源是从一个与它本身提供的第一个资源的不同的域名时,一个资源会发起一个跨域HTTP请求(Cross-site HTTP request).比如说,域名A ( http://domaina ...

  2. springboot跨域请求

      首页 所有文章 资讯 Web 架构 基础技术 书籍 教程 Java小组 工具资源 SpringBoot | 番外:使用小技巧合集 2018/09/17 | 分类: 基础技术 | 0 条评论 | 标 ...

  3. ajax 跨域 headers JavaScript ajax 跨域请求 +设置headers 实践

    解决跨域调用服务并设置headers 主要的解决方法需要通过服务器端设置响应头.正确响应options请求,正确设置 JavaScript端需要设置的headers信息 方能实现. 此处手札 供后人参 ...

  4. 【转】ajax 跨域 headers JavaScript ajax 跨域请求 +设置headers 实践

    解决跨域调用服务并设置headers 主要的解决方法需要通过服务器端设置响应头.正确响应options请求,正确设置 JavaScript端需要设置的headers信息 方能实现. 此处手札 供后人参 ...

  5. 跨域请求设置withCredentials

    最近在做运动城项目,这一个项目下面有多个子项目,如主数据项目,pos项目等.主数据项目的域名为www.topmall.com,POS项目的域名为pos.topmall.com.即两个项目的主域名相同, ...

  6. Chrome本地跨域请求设置,实现HTML模板页

    按照需求,公司现在需要通过第三方的API反馈的数据,进行在本地就可以打开的静态页面程序(完全脱离IIS等服务器).为了更好的维护项目,需要实现静态HTML引入HTML模板,完成ASP.NET模板页的类 ...

  7. Asp.Net Core2.0允许跨域请求设置

    1.services /// <summary> /// /// </summary> /// <param name="services">& ...

  8. ASP.NET MVC 允许跨域请求设置

    场景:创建一个图片上传的站点,用于其他站点跨域上传附件和图片之类. 上传插件结合百度的 webuploader.js 经常会碰到,跨域的问题,如下, 处理方式呢,是在web.config 中配置允许跨 ...

  9. Vue应用请求SpringBoot API出现 CORS 跨域请求设置 Invalid CORS request错误

    1.全局配置 在application.java文件添加CorsRegistry配置 package com.ypnh.authority; import com.ypnh.authority.inf ...

随机推荐

  1. 整合Kafka+Flink 实例(第二部分 设计思路)

    前     言 拖了蛮久了,一直说要接着上一部分写设计思路以及代码,因为自己技术底子薄弱,加上人又懒,所以一直没能继续,今天补上设计思路及部分代码,后面有时间我会再补充一些应用性的功能,的确有些忙,希 ...

  2. Asp.Net Core 中IdentityServer4 授权中心之自定义授权模式

    一.前言 上一篇我分享了一篇关于 Asp.Net Core 中IdentityServer4 授权中心之应用实战 的文章,其中有不少博友给我提了问题,其中有一个博友问我的一个场景,我给他解答的还不够完 ...

  3. 手撸MyBatis从配置文件到读出数据库的模拟实现

    手动模拟MyBatis入门案例的底层实现: 需要了解的关键技术: java反射.动态代理(comming soon) 一.Mybatis入门案例 点击此处跳过入门案例 首先看一下MyBatis最基础的 ...

  4. java 泛型简介(转载)

    原文出处: absfree 1. Why ——引入泛型机制的原因 假如我们想要实现一个String数组,并且要求它可以动态改变大小,这时我们都会想到用ArrayList来聚合String对象.然而,过 ...

  5. Java-正则表达式(新手)

    /* 正则表达式也是一个字符串,用来定义匹配规则,在Pattern类中有简单的规则定义.可以结合字符串类的方法使用. *///创建的一个类.public class LianxiFF1 { //公共静 ...

  6. 为我开发的API添加华丽的外衣

    在日常开发中,最容易被吐槽的就是代码写的烂,没有注释鬼知道你这个是什么意思啊? 另一个就是文档不齐全,这些接口是干嘛的?参数是什么意思?等等问题. 归根到底还是没有严格的开发规范,最重要的还是要有方便 ...

  7. Swift 4.0 数组(Array)之过滤器(filter)的使用

    我们先来定义一个常量整型数组 let array = [5, 4, 3, 1, 2] 过滤器(filter)使用之筛选出大于3的值 let resultArray = array.filter { ( ...

  8. Web_jQuery

    第1章: jQuery简介 为了简化 JavaScript 的开发,一些 JavsScript 库诞生了. JavaScript库封装了很多预定义的对象和实用函数,简化HTML与JavaScript之 ...

  9. [剑指offer]3.数组中的重复数字

    3.数组中的重复数字 题目 找出数组中重复的数字. 在一个长度为 n 的数组 nums 里的所有数字都在 0-n-1 的范围内.数组中某些数字是重复的,但不知道有几个数字重复了,也不知道每个数字重复了 ...

  10. 【洛谷】P2444 [POI2000]病毒——AC自动机

    题目链接 题目描述 二进制病毒审查委员会最近发现了如下的规律:某些确定的二进制串是病毒的代码.如果某段代码中不存在任何一段病毒代码,那么我们就称这段代码是安全的.现在委员会已经找出了所有的病毒代码段, ...