0
点赞
收藏
分享

微信扫一扫

高级MySQL数据库备份脚本

古得曼_63b6 2024-09-03 阅读 29

在这个示例中,我们首先使用 fetch() 发起一个GET请求到 apiURL。如果响应状态码表示成功(即 response.ok 为 true),我们将响应体转换为JSON。
然后,我们创建一个新的 Response 对象 newResponse,其中包含自定义的JSON字符串和一些自定义的响应头。这个新的 Response 对象具有200状态码和"OK"状态信息。
最后,我们解析这个新的 Response 对象中的JSON数据,并在控制台中打印出来。如果在请求或处理过程中发生错误,我们将在 catch 块中捕获并打印错误信息。
请注意,这个示例中的 newResponse.json() 是为了演示如何使用 Response 对象。在实际应用中,通常不需要手动解析 Response 对象中的JSON,因为 fetch() 已经为我们处理了这一步。这里的 newResponse 仅用于演示目的。

<html>
    <head>
        <meta http-equiv="content-type" content="text/html;charset=UTF-8"/>
        <title>测试Request()对象发送请求</title>
    </head>
    <body>
        <script>
           const apiUrl='requestTest.php';
           fetch(apiUrl)
           .then(response=>{
            if(!response.ok)
                {
                    throw new Error('network response was not ok');
                }
                return response.json();
           })
           .then(data=>{
                console.log('fetch data:',data);
                const newHeaders=new Headers({
                    'Content-Type':'application/json',
                    'X-Custom-Header':'CustomValue'//设置标头大多用于令牌或加密之类
                });

                const newResponse=new Response(
                    JSON.stringify({message:'Custom response',data:data}),
                    {
                        status:200,
                        statusText:'ok',
                        headers:newHeaders
                    }
                );
                return newResponse.json();
           })
           .then(customData=>{
                console.log(customData);
           })
           .catch(error=>{
                console.log(error);
           })
           
        </script>
    </body>
</html>
举报

相关推荐

0 条评论