1.什么是Ajax跨域问题
客户端Client通过Ajax方式向服务器Server发送Ajax请求,想要得到响应数据,但是由于客户端和服务器不在同一个域(协议,域名或端口不一致),浏览器出于安全方面的考虑,会在Ajax请求的时候作校验,校验不通过时浏览器会在控制台会抛出一个类似于SEC7120: [CORS] 原点“http://localhost:8080”未在“http://localhost:8081/ajaxserver/hello”的 cross-origin资源的 Access-Control-Allow-Origin response header 中找到“http://localhost:8080”的跨域安全问题
2.为什么会产生Ajax跨域问题
*浏览器限制:通俗一点讲就是浏览器多管闲事,当发现客户端和服务器不在同一个域中时会对Ajax请求做校验,校验不通过就会产生跨域安全问题,并非服务器不允许客户端访问(以下示例可以验证)。
*跨域:当客户端和服务器的协议,域名,端口有一样不一致时,浏览器就会认为是跨域。
*XMLHttpRequest请求(Ajax请求):如果发出的不是XMLHttpRequest请求,浏览器也不会报跨域问题(以下示例可以验证)。
3.Ajax跨域问题示例(基于SpringBoot)
创建服务器端:
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/ajaxserver")
public class AjaxServerController {
@RequestMapping("hello")
public String getString(){
System.out.println("************");
return "Hello world!";
}
}
添加配置:
#配置端口号
server.port=8081
#热部署生效
spring.devtools.restart.enabled=true
验证服务器端(浏览器访问http://localhost:8081/ajaxserver/hello):
创建客户端:
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/ajaxclient")
public class AjaxClientController {
@RequestMapping("/index")
public String getIndex(){
return "index";
}
}
创建静态页面index.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Ajax跨域请求</title>
<!-- <script type="text/javascript" src="js/jquery-3.2.1.min.js"></script> -->
<!-- 引入静态资源文件-->
<script th:src="@{/static/js/jquery-3.2.1.min.js}" type="text/javascript"></script>
</head>
<body>
<a href="#" οnclick="getRequest();">Ajax跨域请求</a>
<script type="text/javascript">
function getRequest(){
console.log("getRequest");
$.ajax({
url:"http://localhost:8081/ajaxserver/hello",
dataType:"JSON",
type:"POST",
async:true,
success:function(data){
console.log(data);
}
});
}
</script>
</body>
</html>
添加配置:
############################################################
#
# thymeleaf相关配置
#
############################################################
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.mode=HTML5
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.content-type=text/html
#加载静态资源文件
spring.mvc.static-path-pattern=/static/**
引入依赖:
<!-- 引入thymeleaf依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
启动客户端,访问http://localhost:8080/ajaxclient/index
点击Ajax跨域问题链接,可以看到如下信息:
浏览器控制台抛出如下错误信息:SEC7120: [CORS] 原点“http://localhost:8080”未在“http://localhost:8081/ajaxserver/hello”的 cross-origin 资源的 Access-Control-Allow-Origin response header 中找到“http://localhost:8080”。