测试接口是否支持跨域

通常情况,前后端项目分离,后端需要设置允许跨域,跨域配置完成后,如何测试接口跨域是否成功?
方案如下:
在这里插入图片描述

新建HTML文件,将下面代码拷贝,运行即可。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>跨域测试</title>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://cdn.staticfile.org/bootstrap/4.5.3/css/bootstrap.min.css" >
</head>
<body>
<div class="container">
    <h1 style="margin-top:50px">跨域测试</h1>
    <!-- Content here -->
    <p class="text-left">API地址:</p>
    <input type="text" style="width:600px;height:30px;font-size:14px;" id="urlText" value=""/>
    <p>&nbsp;
    <p/>
    <p class="text-left">Token:</p>
    <input type="text" style="width:600px;height:30px;font-size:14px;" id="tokenTxt"  value=""/>
    <p>&nbsp;
    <p/>
    <input type="button" class="btn btn-outline-primary" id="cors" value="验证跨域"/>
</div>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://cdn.staticfile.org/jquery/3.4.1/jquery.min.js" ></script>
<script src="https://cdn.staticfile.org/popper.js/1.8.0/popper.min.js" ></script>
<script src="https://cdn.staticfile.org/bootstrap/4.5.3/js/bootstrap.min.js" ></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("Authorization", "Bearer " + $("#tokenTxt").val());
                }
            },
            success: function (data) {
                alert("success");
            },
            error:function(data){
				alert("failed");
            }
        })
    });
</script>
</body>
</html>

  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值