使用Access-Control-Allow-Origin解决跨域

什么是跨域

当两个域具有相同的协议(如http), 相同的端口(如80),相同的host(如www.google.com),那么我们就可以认为它们是相同的域(协议,域名,端口都必须相同)。

跨域就指着协议,域名,端口不一致,出于安全考虑,跨域的资源之间是无法交互的(例如一般情况跨域的JavaScript无法交互,当然有很多解决跨域的方案)

Spring 提供了三种方式:

  1. CorsFilter 过滤器
  2. <mvc:cors> Bean
  3. @CrossOrigin 注解

这三种方式,本质上都是用来配置 CorsConfiguration。

11.1 CorsFilter

首先,依赖 CorsFilter 创建自己的过滤器:

public class MyCorsFilter extends CorsFilter {
public MyCorsFilter() {
super(configurationSource());
} private static UrlBasedCorsConfigurationSource configurationSource() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); CorsConfiguration config = new CorsConfiguration();
config.setAllowedOrigins(Collections.singletonList("http://domain.com"));
config.setAllowCredentials(true); CorsConfiguration config2 = new CorsConfiguration();
config2.setAllowedOrigins(Collections.singletonList("http://domain.com"));
config2.setAllowCredentials(true); source.registerCorsConfiguration("/**", config);
source.registerCorsConfiguration("/xxx", config2); return source;
}
}

然后,将其注册为一个过滤器即可。

11.2 <mvc:cors>

<mvc:cors>
<mvc:mapping path="/xxx"
allowed-origins="http://localhost:7070"
allowed-methods="GET, POST"
allowed-headers="Accept-Charset, Accept, Content-Type"
allow-credentials="true" />
<mvc:mapping path="/yyy/*"
allowed-origins="*"
allowed-methods="*"
allowed-headers="*" />
</mvc:cors>

11.3 @CrossOrigin

// 将跨域设置在类上,那么所有的 mapping 都会使用这个策略
// 如果不加参数,那么将会使用配置中的默认参数
@CrossOrigin
public class CORSController {
public String cors(@RequestParam(defaultValue = "callback") String callback, HttpServletResponse response) {
// 最原始的方式,手动写请求头
response.setHeader("Access-Control-Allow-Origin", "http://192.168.163.1:8081");
return callback + "('hello')";
} // 将跨域设置在方法上
@RequestMapping("/cors")
@CrossOrigin(origins = {"http://localhost:8080", "http://remotehost:82323"},
methods = {RequestMethod.GET, RequestMethod.POST},
allowedHeaders = {"Content-Type", "skfjksdjfk"},
allowCredentials = "true",
maxAge = 1898978
)
@RequestMapping("/rrr")
public String rrr(@RequestParam(defaultValue = "callback") String callback) {
return callback + "('rrr')";
}
}

不使用注解模式:

package com.nf147.manage.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpServletResponse; @RestController
public class CorsConstroller {
@RequestMapping("/cors")
public String cors (@RequestParam(defaultValue = "callback") String callback, HttpServletResponse response) {
     //使用Access-Control-Allow-Origin解决跨请求
      response.setHeader("Access-Control-Allow-Origin", "http://169.---236.45:8080"); 注意这里要和本地服务器的url一致
      return callback + "('hello')";
    }
}

请求页面:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.js"></script>
</head>
<body>
<button onclick="fasong()">发送</button>
</body> <script> const url = 'http://localhost:9999'; function fasong () {
fetch(url + "/cors", {
method: 'get',
}).then(resp => resp.text())
.then(console.log);
} function fasong232() {
$.ajax({
method: 'get',
url: url + "/cors",
dataType: 'jsonp',
jsonpCallback: 'hehehe',
jsonp: 'xxxxxxxxxxxxxxxxxxxxxxx'
}).done((data) => {
console.log(3333333333333333, data);
}).fail((x, y, z) => {
console.error(x, y, z);
})
} function loadScript(src) {
const script = document.createElement('script');
script.src = src;
document.body.appendChild(script);
} function fason2g() {
if (window.confirm('是否发送?')) {
loadScript(`${url}/cors?callback=aaa`);
} else {
loadScript(`${url}/rrr?callback=bbb`);
}
} function aaa(c) {
alert(c);
} function bbb(c) {
console.log(c);
} function fasong2() {
if (window.confirm('是否发送?')) {
$.ajax({
method: 'get',
url: url
}).done((data) => {
console.log(data);
}).fail((x, y, z) => {
console.error(x, y, z);
})
}
}
</script> </html>

我这里是用node搭建了一个本地服务器

教程地址:https://www.cnblogs.com/nongzihong/p/10021033.html

效果演示:

最新文章

  1. FIFO跨时钟域读写
  2. POJ 3260 多重背包+完全背包
  3. ADB无线连接
  4. js获取手机型号和手机操作系统版本号
  5. Elasticsearch 与 Kafka 整合剖析
  6. arrow functions 箭头函数
  7. [HNOI2008]遥远的行星
  8. mysql Navicat客户端
  9. Java 虚拟机的内存溢出
  10. 前端开发环境webstorm搭建
  11. 搜狐eHR团队-曾经一起奋斗过的~
  12. char varchar
  13. IP与十进制相互转化
  14. day05-if-else语句
  15. vue ui之 iview 事件拦截
  16. TensorFlow的梯度裁剪
  17. JS 01 变量_数据类型_分支循环_数组
  18. C# 中正则表达式 Group 分组【转】
  19. 安全控制 iptables
  20. 编译skia静态库时,图片解码库无法注册的问题

热门文章

  1. [LeetCode]220. 存在重复元素 III
  2. [转载]Jupyter notebook调试
  3. httpClient4.5.2工具类总结
  4. js实现倒计时(分:秒)
  5. Oracle 之 触发器
  6. C#实现Base64处理加解密
  7. [HAOI2010]软件安装(Tarjan,树形dp)
  8. angularjs 结构的两种写法(2)
  9. dubbo网关
  10. iOS中延迟执行和取消的几种方式