我正在为学生构建一个简单的页面来测试他们编写的 API 的 PUT 操作。学校、计算机现在允许邮递员在上面,因为这被视为安全风险。
有没有办法获取详细响应,以便我可以将其输出到 DOM?一切都很顺利,我只是无法得到详细的回复。我得到的只是
[object HTMLParagraphElement]
。
function sendData() {
const url = document.getElementById('url').value;
const data = document.getElementById('json').value;
fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json; charset=UTF-8',
},
body: JSON.stringify(data),
})
.then(response => response.json())
.then(data => console.log(data))
.catch((error) => {
console.error('Error:', error);
document.getElementById("response").innerHTML = response;
});
当我想要响应代码、标头和正文时,输出为
[object HTMLParagraphElement]
。
代码中的主要问题是您尝试将响应对象直接分配给 DOM,这会导致 [object HTMLParagraphElement]。您需要处理响应对象并正确格式化它。
以下是如何调整 sendData 函数以捕获并以详细方式显示响应:
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>API Tester</title>
</head>
<body>
<input type="text" id="url" placeholder="Enter API URL" />
<textarea id="json" placeholder="Enter JSON body"></textarea>
<button onclick="sendData()">Send PUT Request</button>
<div id="response"></div>
<script>
function sendData() {
const url = document.getElementById('url').value;
const data = JSON.parse(document.getElementById('json').value); // Ensure proper JSON parsing
const responseDiv = document.getElementById("response");
fetch(url, {
method: 'PUT', // Change to PUT
headers: {
'Content-Type': 'application/json; charset=UTF-8',
},
body: JSON.stringify(data),
})
.then(async (response) => {
// Capture the response details
const status = `Status: ${response.status} ${response.statusText}`;
const headers = `Headers: ${[...response.headers.entries()].map(h => h.join(': ')).join('\n')}`;
// Parse response body as JSON
const body = await response.json();
// Create a verbose response message
const verboseResponse = `
<p><strong>${status}</strong></p>
<p><pre>${headers}</pre></p>
<p><pre>Body: ${JSON.stringify(body, null, 2)}</pre></p>
`;
// Output the detailed response to the DOM
responseDiv.innerHTML = verboseResponse;
})
.catch((error) => {
console.error('Error:', error);
responseDiv.innerHTML = `<p style="color: red;">Error: ${error}</p>`;
});
}
</script>