现在的位置: 首页 > 编程语言 > 正文

springboot跨域CORS处理代码解析

2020年02月13日 编程语言 ⁄ 共 1822字 ⁄ 字号 评论关闭

这篇文章主要介绍了springboot跨域CORS处理代码解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

一 源(Origin)

源指URL的协议,域名,端口三部分组成,如果这个三个成分都相同,就判定是同源,否则为不同源。同源策略(Same origin policy)是一种浏览器的约定,即在浏览器中禁止非同源访问。

二 CORS

CORS即"跨域资源共享"(Cross-origin resource sharing),是一个W3C标准。它允许浏览器向跨源服务器,发出XMLHttpRequest请求,从而克服了ajax只能同源使用的限制。springboot也提供了cors的解决方法。下面将模拟浏览器跨域,并解决跨域问题。

三 provider工程

provider工程提供了一个接口给外部访问,端口是8080。

/** * @Author lsc * @Description <p> cors </p> * @Date 2019/10/20 21:32 * @Version 1.0 */@RestControllerpublic class ProviderController { @GetMapping("youku1327") public String getUser(){ System.out.println("---------"); return "hello youku1327"; }}

四 consumer

consumer 提供访问页面,跨域亲求 provider接口,端口为8082。

控制层代码:

/** * @Author lsc * @Description <p> </p> * @Date 2019/10/20 21:32 * @Version 1.0 */@Controllerpublic class ComsumerController { @GetMapping("youku1327") public String getUser(){ return "index"; }}

页面代码:

<!DOCTYPE html><html lang="en" xmlns:th="http://www.thymeleaf.org"><head> <meta charset="UTF-8"> <title>cors-youku1327</title></head><body><script th:src="@{jquery-1.8.3.js}" type="text/javascript"></script><button id="button">获得用户</button><script> $("#button").click(function () { $.ajax({ url: "http://localhost:8080/youku1327", type: "get", success:function (result) { console.log(result); } }) });</script></body></html>

五 跨域问题产生

两个项目分别启动后,在流量器中访问consumer,报错如下,不存在允许访问的请求头。

六解决方案

在provier实现WebMvcConfigurer接口,或者使用@CrossOrigin注解在方法上。

示例代码:

/** * @Author lsc * @Description <p> </p> * @Date 2019/10/20 23:15 * @Version 1.0 */@Configurationpublic class WebConfig implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedOrigins("http://localhost:8082") .allowCredentials(true) .allowedMethods("GET", "POST", "DELETE", "PUT","PATCH") .allowedHeaders("*"); }}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

本文标题: springboot跨域CORS处理代码解析

以上就上有关springboot跨域CORS处理代码解析的相关介绍,要了解更多springboot,跨域,CORS,处理内容请登录学步园。

抱歉!评论已关闭.