控制台获取和执行请求
时间:2025-8-26 09:20 作者:六度科技 分类: JS
获取请求
(() => {
const originFetch = window.fetch;
/* 工具:递归替换超长字符串 */
const replaceLong = (obj) => {
if (typeof obj === 'string') {
return obj.length > 200 ? '测试文字' : obj;
}
if (Array.isArray(obj)) {
return obj.map(replaceLong);
}
if (obj && typeof obj === 'object') {
const res = {};
for (const [k, v] of Object.entries(obj)) {
res[k] = replaceLong(v);
}
return res;
}
return obj;
};
/* 包装 fetch */
window.fetch = async (...args) => {
const [url, opts = {}] = args;
const { method = 'GET', body } = opts;
const log = { url, method: method.toUpperCase() };
/* 1. 请求体(POST/PUT/PATCH) */
if (body && /^(POST|PUT|PATCH)$/i.test(method)) {
const raw = typeof body === 'string' ? body : JSON.stringify(body);
try {
log.sent = replaceLong(JSON.parse(raw));
} catch {
log.sent = replaceLong(raw); // 非 JSON 原样输出
}
}
/* 2. 发送请求 */
const resp = await originFetch(...args);
const clone = resp.clone();
/* 3. 响应体 */
const text = await clone.text();
try {
log.received = replaceLong(JSON.parse(text));
} catch {
log.received = replaceLong(text); // 非 JSON 原样输出
}
/* 4. 打印 */
console.log('📤 log:', log);
return resp;
};
console.log('✅ fetch 监听已开始');
})();
发送请求(适合携带参数无加密 cookie有动态)
(async () => {
const api = {
url: '请求地址',
data: {
gameId: '10011',
pageIndex: 1,
pageSize: 16,
bizProd: 1,
type: '1',
posType: 1,
filterDTOList: [],
sortAttrId: '',
sortType: 2,
combineFilterList: []
}
};
try {
const res = await fetch(api.url, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(api.data)
});
const jsonText = await res.text(); // ← 直接拿原始 JSON 字符串
console.log(jsonText); // 控制台打印
return jsonText; // 返回给调用方
} catch (e) {
console.error('? 调用失败:', e);
return JSON.stringify({ success: false, message: e.message });
}
})();