全部 ApiPost使用 后端 前端 接口测试 IOS Android 数据库 2022 测试技术 工具
问答 / 问答详情

如何在html中加header

前端 721次浏览

用APIpost get+header参数,从网上成功读回json数据,用python“requests.get(url,Sensor,headers=header)”也能读回json数据,我的问题是,用以下的html

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <meta http-equiv="X-UA-Compatible" content="ie=edge">

    <title>JaaleeGet1</title>

<style>       

        .btn {

            height: 30px;

            width: 100px;

            background: black;

            margin: 10px 0;

            text-align: center;

            line-height: 30px;

            color: #fff;

        }

 </style>

 <script type="text/javascript">

        window.onload = function() {

            var value = document.getElementById("value");

            value.innerHTML = "Value : undefined";

            //get请求

            document.querySelector(".getbtn").onclick = function() {

           console.log("Get请求");

                var xmlhttp = new XMLHttpRequest();

                // get方法带参数是将参数写在url里面传过去给后端

                xmlhttp.open("GET", "https://sensor.jaalee.com/v1/open/htplu?bleMac=d136a1aab939",true);

                xmlhttp.setRequestHeader("Authorization","Of4eLtMZA4GN51YDU0MR+VBJxsVtAElSm8na9bHTWnQ=");    

                xmlhttp.send();

                // readyState == 4 为请求完成, status == 200 为请求成功返回的状态

                xmlhttp.onreadystatechange = function() {

                    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {

                        console.log(xmlhttp.responseText);

                        var jsonObj = JSON.parse(xmlhttp.responseText)

                        console.log(jsonObj.data.current_value);

                        value.innerHTML = "vaule : " + jsonObj.data.current_value;

                    }

                }

            };

        }

    </script>

</head>

<body>

    <!-- <button type="submit" id="btn" class="req"> 获取请求 </button> -->

    <!-- <button class="postbtn btn">POST请求</button> -->

    <button class="getbtn btn">GET请求</button>

    <p id="value"></p>

</body>

</html>

<!DOCTYPE html>

不加 xmlhttp.setRequestHeader("Authorization","Of4eLtMZA4GN51YDU0MR+VBJxsVtAElSm8na9bHTWnQ="); 能成功从服务器读到返回的“读数据失败!”信息,加上这句浏览器报错“跨域错误”,不能读回数据,请问在html中如何才能正确的加入header信息。

| 1 收藏
  • lindx
  • 2021-07-07 提问

3 个回答

跟后台设置有关,联系后端人员添加允许请头 Authorization或者Origin 允许为*

用APIpost或Python+Header可以正确的读回数据,而上述的html+Header则报CROS错,我想问上述html没毛病吗?

  • lindx
  • 2021-07-08 回答
跨域问题,在常规浏览器环境下,此问题前端能做的工作不多。
Apipost 私有化火热进行中

撰写答案

只服务于

前后端、移动端、测试人员

提问题 发布您遇到的Bug和问题,上万名大牛和开发者来帮您解决!