首页 > 解决方案 > 如何在控制台中打印请求正文?

问题描述

我有一个javascript代码,我想向API发送一个http请求并获得响应,我能够做到这一点,但是有没有办法可以在控制台中打印我的请求正文?

  <html>
        <body>
            <script>
     // POST request using fetch() 
var user="hello";
    fetch("url", 
    { 

        // Adding method type 
        method: "POST", 

        // Adding body or contents to send 
        body: JSON.stringify({ 
            empUUID : user, 
            body: "bar", 
            userId: 1 ,
            id: id
        }), 

        // Adding headers to the request 
        headers: { 
            "Content-type": "application/json; charset=UTF-8"
        }
    }) 

    // Converting to JSON 
    .then(response => response.json()) 

    // Displaying results to console 
    .then(json => console.log(json)); 


                }

            </script>

        </body>
    </html>

标签: javascripthtmlapi

解决方案


使用变量,然后在收到如下响应时打印您的请求:

<html>
        <body>
            <script>
    // POST request using fetch() 
    var user="hello";
    let request = { 
        empUUID : user, 
        body: "bar", 
        userId: 1 ,
        id: id
    };
    fetch("url", 
    { 

        // Adding method type 
        method: "POST", 

        // Adding body or contents to send 
        body: JSON.stringify(request), 

        // Adding headers to the request 
        headers: { 
            "Content-type": "application/json; charset=UTF-8"
        }
    }) 

    // Converting to JSON 
    .then(response => response.json()) 

    // Displaying results to console 
    .then(json => console.log("request:", request, ", response:", json)); 


                }

            </script>

        </body>
    </html>

推荐阅读