使用fetch()请求后console.log无法打印服务器JSON响应的问题排查
无法打印fetch返回的JSON响应(网络面板可见响应)
我在某信用卡网站中使用脚本向localhost发送交易数据,服务器已准确接收并成功返回JSON响应,但console.log完全无法打印该响应。我能在开发者工具的网络面板中看到响应内容,想了解无法打印的原因。
尝试的代码
Async/Await版本
async function sendData(username, transactions) { let apiUrl = "http://localhost:3100/api"; let postOptions = { method: "POST", cache: "no-cache", headers: { "Content-Type": "application/json", }, redirect: "follow", referrerPolicy: "no-referrer", body: JSON.stringify({ username, transactions }), }; try { let response = await fetch(apiUrl, postOptions); if (!response.ok) { throw new Error(`Response status: ${response.status}`); } let serverMessage = await response.json(); console.log(serverMessage); } catch (error) { console.log(error.message); } }
Promise链式调用版本
function sendData(username, transactions) { let apiUrl = "http://localhost:3100/api"; let postOptions = { method: "POST", cache: "no-cache", headers: { "Content-Type": "application/json", }, redirect: "follow", referrerPolicy: "no-referrer", body: JSON.stringify({ username, transactions }), }; fetch(apiUrl, postOptions) .then((res) => res.json()) .then((msg) => console.log(msg)) .catch((e) => console.log(e)); }
补充说明
- 使用Chrome的JS注入扩展(如Scripty)运行相同代码并配合前端触发时,能正常打印响应;但手动在控制台调用
sendData函数则无法打印。
问题解决
经详细排查发现,问题实际出在该信用卡网站对console.log的篡改上:
- 网站将
console.log的name属性设为空字符串,arguments设为null,导致其无法正常执行打印操作。
将代码中所有的console.log替换为console.info后,即可正常打印响应内容,这显然是网站自身的限制问题。
内容的提问来源于stack exchange,提问作者Hamid Ali
相关产品推荐
相关产品推荐

