Chrome调试技巧

总结摘要
Chrome调试技巧

Chrome 开发者控制台的 Console 页使用 fetch 命令调试接口技巧

在 Chrome 开发者控制台的 Network 页可以获取请求的 fetch 格式。

“Copy”–>“Copy as fetch”

注意事项

  1. Chrome 开发者控制台的 Console 不展示 log 级别的日志,原因未知。因此使用 error 级别的日志展示信息。
  2. 下载文件时,建议使用准确的文件扩展名。例如 Excel 格式的文件的文件名称应当使用文件扩展名 .xlsx 或 .xls,Tar.gz 格式的文件的文件名称应当使用文件扩展名 .tar.gz。
  3. 上传文件时,应当注意,需要删除Content-Type属性,完全由 "body": formData自动指定。

普通GET、PUT,文件上传、文件下载接口都可以使用。

fetch 命令打印结果

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
.then(response => {
  if (!response.ok) {
    console.error("Fetch 请求失败 text:", response.text());
    console.error("Fetch 请求失败 statusText:", response.statusText);
    throw new Error(`HTTP error! status: ${response.status} ${response.statusText}`);
  }
  return response.json();
})
.then(data => {
  console.error("Fetch 请求返回的数据:", data);
})
.catch(error => {
  console.error("Fetch 请求失败:", error);
});

fetch 下载文件

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29

.then(response => {
    if (!response.ok) {
        throw new Error('Network response was not ok');
    }

    // 打印所有响应头
    for (let [key, value] of response.headers.entries()) {
        console.log(`${key}: ${value}`);
    }
    return response.blob();  // 将响应体转换为Blob对象
})
.then(blob => {
    // 创建一个链接元素
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.style.display = 'none';
    a.href = url;
    a.download = 'test_download.tar.gz';  // 使用用户选择或预设的文件名
    document.body.appendChild(a);
    a.click();  // 模拟点击以下载文件

    // 延迟清理
    window.URL.revokeObjectURL(url);
    document.body.removeChild(a);
})
.catch(error => {
    console.error('There was an error!', error);
});

fetch 上传文件
约束条件,Chrome Console 安全约束禁止直接读取本地文件,因此需要一个上传文件的过程。

  1. 将如下 HTML 代码嵌入到页面中。
  2. 执行 fetch 命令
1
2
<input type="file" id="fileInput">
<button>Upload File</button>
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
let fileInput = document.getElementById('fileInputBulk');
let formData = new FormData();
formData.append('file', fileInput.files[0]);

fetch("https://url ", {
  "headers": {
    "accept": "*/*",
    "cftk": "",
    "csrf": "",
    "sec-ch-ua-platform": "\"Windows\"",
    "sec-fetch-mode": "cors",
    "sec-fetch-site": "same-origin",
    "x-language": "zh-cn"
  },
  "referrer": "url",
  "referrerPolicy": "strict-origin-when-cross-origin",
  "body": formData,
  "method": "POST",
  "credentials": "include"
})
.then(response => {
    if (!response.ok) {
      console.error("Fetch 请求失败 text:", response.text());
      console.error("Fetch 请求失败 statusText:", response.statusText);
      throw new Error(`HTTP error! status: ${response.status} ${response.statusText}`);
    }
    return response.json();
  })
  .then(data => {
    console.error("Fetch 请求返回的数据:", data);
  })
  .catch(error => {
    console.error("Fetch 请求失败:", error);
  });

END