SpringBoot使用Cors开启跨域

  • 一、为什么要跨域?

跨域问题来源于JavaScript的【同源策略】,即只有【协议+主机名+端口号】相同,则允许相互访问。也就是说JavaScript只能访问和操作自己域下的资源,不能访问和操作其他域下的资源。跨域问题是针对JS和Ajax的,HTML本身没有跨域问题,比如a标签、script标签、甚至form标签(可以直接跨域发送数据并接收数据)等。

  • 二、实现跨域的两种方式

1、JSONP

1.AJAX直接请求普通文件存在跨域无权限访问的问题,不管是静态页面也好
2.不过我们在调用js文件的时候又不受跨域影响,比如引入jQuery框架的,或者是调用相片的时候
3.凡是拥有src这个属性的标签都可以跨域例如<script><img><iframe>
4.如果想通过纯web端跨域访问数据只有一种可能,那就是把远程服务器上的数据装进js格式的文件里.
5.而Json又是一个轻量级的数据格式,还被js原生支持
6.为了便于客户端使用数据,逐渐形成了一种非正式传输协议,人们把它称作JSONP,该协议的一个要点就是允许用户传递一个callback 参数给服务端

传统的跨域方案是JSONP,JSONP虽然能解决跨域但是有一个很大的局限性,那就是只支持GET请求,不支持其他类型的请求。

2、Cors

Cors(跨域源资源共享)
(Cors,Cross-origin resource sharing)是一个W3C标准它是一份浏览器技术的规范
它提供了Web服务从不同网域传来沙盒脚本的方法,以避开浏览器的同源策略
这是JSONP模式的现代版

我们今天主要学习Cors的跨域方法

  • 三、开始跨域

首先,我们需要创建两个SpringBoot项目,一个服务提供者(provider),一个服务消费者(consumer),只需要引入以下依赖即可:

<!-- web支持 -->
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- thymeleaf模板引擎 -->
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

,然后我们修改服务提供者(provider)的application.yml文件,加入配置信息:

#提供服务的端口号
server:
  port: 8080

在服务提供者(provider)项目中的resource目录下的templates目录下新建一个html文件:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Cors跨域请求</title>
    <script type="text/javascript" th:src="@{/js/jquery-3.2.0.min.js}"></script>
</head>
<body>
<input type="button" onclick="getRequest()" value="GET请求">
<input type="button" onclick="postRequest()" value="POST请求">
<script>
    function getRequest() {
        $.get('http://localhost:8081/index', function (res) {
            $('body').html(res);
        })
    }

    function postRequest() {
        $.post('http://localhost:8081/index', function (res) {
            $('body').html(res);
        })
    }
</script>
</body>
</html>

然后我们修改服务消费者(consumer)的application.yml文件,加入配置信息:

#消费服务的端口号
server:
  port: 8081

然后新建一个controller,在controller包下面新建一个IndexController文件:

package com.zyxx.cors.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author lizhou
 * @date 2019/8/16
 */
@RestController
public class IndexController {

    @GetMapping("index")
    public String gindex() {
        return "get hello;";
    }

    @PostMapping("index")
    public String pindex() {
        return "post hello;";
    }
}

接下来,我们启动这两个项目:访问 http://localhost:8080/,点击页面中的按钮,会出现以下提示错误:

Access to XMLHttpRequest at 'http://localhost:8081' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

这是提醒我们,在http://localhost:8081中访问http://localhost:8080,受到了限制,原因是我们没有开启跨域,我们有两种方法开启跨域

1、@CrossOrigin()

@CrossOrigin(value = "http://localhost:8081")
@GetMapping("index")
public String gindex() {
    return "get hello;";
}
    
@CrossOrigin(value = "http://localhost:8081")
@PostMapping("index")
public String pindex() {
    return "post hello;";
}

在controller请求的方法上加上该注解,即表示该接口开启了跨域,允许http://localhost:8081进行访问

2、Config配置文件

以上加注解在方法上显得很繁杂,我们可以将整个项目配置为开启跨域,在config包下面新建一个CorsConfig文件:

package com.zyxx.cors.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * @author lizhou
 * 跨域配置
 * @date 2019/8/16
 */
@Configuration
public class CorsConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        // 所有请求都会处理跨域
        registry.addMapping("/**")
                // 允许谁访问
                .allowedOrigins("http://localhost:8081")
                // 允许通过的请求数
                .allowedMethods("*")
                // 允许的请求头
                .allowedHeaders("*");
    }
}

这样,我们整个项目就都开启了跨域,可以随意访问了。

如您在阅读中发现不足,欢迎留言!!!

发布了63 篇原创文章 · 获赞 66 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_40065776/article/details/99685252
今日推荐