前言
一个HTML网页,用于测试SpringBoot接口的跨域访问
一、HTML代码
<!DOCTYPE html>
<head>
<meta charset="UTF-8">
<title>cors test</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
</head>
<body>
<div class="container" align="center">
<h1>Cors Test</h1><br/>
<p>input your target api address:</p>
<input type="text" style="width:600px;height:30px;font-size:14px;" id="urlText"/><br/><br/><br/>
<p>input your token:</p>
<input type="text" style="width:600px;height:30px;font-size:14px;" id="tokenTxt" value=""/><br/><br/>
<input type="button" class="btn btn-outline-primary" id="cors" value="CHECK CORS"/>
</div>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
<script type="text/javascript">
$("#cors").on('click', function (event) {
event.preventDefault();
var url2 = $("#urlText").val();
$.get({
contentType: 'application/x-www-form-urlencoded;charset=UTF-8',
url: url2,
beforeSend: function (xhr) {
if ($("#tokenTxt").val().trim()) {
/* Authorization header */
xhr.setRequestHeader("token", ""+ $("#tokenTxt").val());
}
},
success: function (data) {
alert("success");
}
})
});
</script>
</body>
</html>
二、使用方法
Win+R 调出运行窗口,输入 notepad 点击 Enter 进入记事本,复制上述代码粘贴到记事本,Crtl+S 保存,保存类型选择所有文件,文件名 Test.html ,浏览器打开该网页,输入测试的 api 地址,点击 CHECK CORS 按钮,若弹出 success 提示框则表示该请求支持跨域,如图:
若没有弹出提示框,键入 F12 打开开发者模式,切换到 Console,若提示 No ‘Access-Control-Allow-Origin’ header is present on the requested resource ,则表示不支持跨域,如图:
总结
如果这篇博客对你有帮助的话,记得给我点个赞,你的鼓励是对我最大的支持!谢谢。◕‿◕。