-
Notifications
You must be signed in to change notification settings - Fork 16
六 16、ajax 跨域访问
ZeroOrInfinity edited this page Dec 14, 2020
·
1 revision
demo 模块 ->
basic-detail-example
<!DOCTYPE html>
<html xmlns:th="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<title>index</title>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/jquery@1.11.1/dist/jquery.min.js"></script>
</head>
<body>
hello <span th:text="${username}">world!</span><br>
roles: <span th:text="${roles}"/>
<!-- 通过 th:action 的方式支持 csrf 或者 添加隐藏域<input type="hidden" th:name="${_csrf.parameterName}" th:value="${_csrf.token}"/> -->
<form th:action="@{/logout?logout}" method="post">
<input type="submit" value="退出登录post"/>
</form>
<br><br>
<h5>启动 basic-detail-example 示例 端口分别为 9090/9091, 跨域设置属性通过 ums.client.cors.xxx 设置, 详情参考 basic-detail-example 中的
application.yml</h5>
<h5>配置跨域时要注意的事项: 要放行跨域的 url 的 OPTIONS 请求的权限, 如 ums.client.cors.urlList=/** 相对应的权限设置为 ums.client.permitUrls ->
/**:OPTIONS</h5>
<a href="#" onclick="testCors()">测试跨域</a>
</body>
<script>
testCors = function () {
$.ajax({
url: 'http://localhost:9091/demo/me',
type: "GET",
dataType: "json",
contentType: 'application/json; charset=UTF-8',
success: function (data) {
console.log("==========测试跨域成功============")
// ...
console.log(data)
// window.location.href = 'http://localhost:9091/demo/me'
},
error: function (data) {
console.log("==========测试跨域失败============")
console.log(data)
}
})
}
</script>
</html>
ums:
client:
# 不需要认证的 uri(可以带 HttpMethod 后缀; 用:隔开), 例如: /user/** 或 /user/**:post, 默认为 空 Set.
permit-urls:
- /**:OPTIONS
# ============= 跨域请求配置 =============
cors:
# 是否支持跨域, 默认为 false;
enable: true
# 允许跨域访问的域,可以是一个域的列表,也可以是通配符"*"。这里要注意 Origin 规则只对域名有效,并不会对子目录有效。
access-control-allow-origin:
- http://localhost:9090
# 是否允许请求带有验证信息, 当为 true 时, accessControlAllowOrigin 不能为 "*", 默认为 true;
access-control-allow-credentials: true
# 进行跨区请求允许曝露的 headers,请求成功后,ajax 可以在 XMLHttpRequest 中访问这些头的信息;
access-control-expose-headers: Authorization
# Set the list of headers that a pre-flight request can list as allowed for use during an actual request.
# The special value "*" allows actual requests to send any header. A header name is not required to be listed
# if it is one of: Cache-Control, Content-Language, Expires, Last-Modified, or Pragma. By default this is not set.
access-control-allow-headers:
- '*'
# 允许进行跨区请求的请求方法
access-control-allow-methods:
- GET
- POST
- PUT
- DELETE
# 缓存此次请求的秒数。在这个时间范围内,所有同类型的请求都将不再发送预检请求而是直接使用此次返回的头作为判断依据,非常有用,大幅优化请求次数
access-control-max-age: PT30S
# 允许进行跨区请求的 url, 支持通配符.
url-list:
- /**