函数内部无法使用fetch怎么办?
  • 板块灌水区
  • 楼主细数繁星
  • 当前回复5
  • 已保存回复0
  • 发布时间2023/6/25 11:32
  • 上次更新2023/11/3 12:27:52
查看原帖
函数内部无法使用fetch怎么办?
824363
细数繁星楼主2023/6/25 11:32

比如以下代码:

var res = fetch('/api/blog/detail/' + BlogGlobals.blogID).then(res => res.json())
        console.log(res);

可以返回正常结果,但是:

function clickBotton(){
        var res = fetch('/api/blog/detail/' + BlogGlobals.blogID).then(res => res.json())
        console.log(res);
        
    };

会报错

Uncaught (in promise) TypeError: Failed to fetch
    at HTMLButtonElement.clickBotton (userscript.html?id=f905148f-9aca-4422-95a1-bff3314b907d:27:19)
clickBotton @ userscript.html?id=f905148f-9aca-4422-95a1-bff3314b907d:27
Promise.then(异步)
clickBotton 
2023/6/25 11:32
加载中...