错误“ TypeError:无法获取”正在使用alert(),但不使用console.log()

发布于 2025-01-18 21:39:24 字数 1074 浏览 1 评论 0原文

“ TypeError:无法获取”页面刷新。

im在我刷新页面时会收到fetch错误“ typeError:typeerror:无法获取”,但是如果我将状态作为获取参数传递,则问题只会发生,否则应用程序运行良好。

这就是代码:

const \[posts, setPosts\] = useState(\[\])

//Get posts
useEffect(() => {
    fetch("https://codeleap-test-api.herokuapp.com/posts", {
        method: "GET",
        headers: {
            "Content-type": "application/json",
        }
    })
        .then(resp => resp.json())
        .then(data => setPosts(data))
        .catch(err => alert(err))
}, [])

// create new post
function createPost(post) {
    fetch("https://codeleap-test-api.herokuapp.com/posts", {
        method: "POST",
        headers: {
            "Content-type": "application/json",
        },
        body: JSON.stringify(post)
    })
        .then(resp => resp.json())
        .then(data => console.log('Posts created'))
        .catch(err => console.log(err))
}`

现在,如果我在第一个使用效果括号内传递状态“帖子”,我总是会收到上面提到的错误。像这样:

//获取ports useffect(()=> {fetch ...},[posts])

我该怎么办来解决问题?

提前致谢!

"TypeError: failed to fetch" on page refresh.

Im getting the fetch error "TypeError: failed to fetch" when I refresh the page, but the issue just happens if i pass a state as fetch parameter, otherwise the application run fine.

That's the code:

const \[posts, setPosts\] = useState(\[\])

//Get posts
useEffect(() => {
    fetch("https://codeleap-test-api.herokuapp.com/posts", {
        method: "GET",
        headers: {
            "Content-type": "application/json",
        }
    })
        .then(resp => resp.json())
        .then(data => setPosts(data))
        .catch(err => alert(err))
}, [])

// create new post
function createPost(post) {
    fetch("https://codeleap-test-api.herokuapp.com/posts", {
        method: "POST",
        headers: {
            "Content-type": "application/json",
        },
        body: JSON.stringify(post)
    })
        .then(resp => resp.json())
        .then(data => console.log('Posts created'))
        .catch(err => console.log(err))
}`

Now, if I pass the state "posts" inside the first useEffect brackets, I always get the error mentioned above. Like that:

//get posts useEffect(() => {fetch...}, [posts])

What can I do to solve the problem?

Thanks in advance!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文