简体   繁体   English

API 调用导致页面重新加载

[英]API call causes page reload

I'm using JS to make API calls in my HTML website.我正在使用 JS 在我的 HTML 网站上拨打 API 电话。 But the page is refresh with DELETE method但是页面是用 DELETE 方法刷新的

    async function delete(param) {
        const response = await fetch(`${api_Url}/products${param}`, {
            method: 'DELETE',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `bearer ${token}`
            },
        }).then((response) => {
            console.log(response);
        })
    };

Response:回复:

body: (...)
bodyUsed: false
headers : heders {}
ok: true
redirect: false
state: 204
statusText : « No content »
type: « CORS »
url : « http://localhost:5678/api/products/9 »
[[Prototype]] : response

And after the request, the page is refreshed并在请求后刷新页面

This function is called by this code:此 function 通过以下代码调用:

    const deleteBtn = document.querySelectorAll('.delete_icon');

    deleteBtn.forEach(element => {
        element.addEventListener('click', event => {
            event.preventDefault();

            const Id = event.currentTarget.id;
            delete(Id);
        });
    });

But this code is not the reason for the refresh.但是这段代码不是刷新的原因。 One thing worked:一件事奏效了:

window.addEventListener('beforeunload', (event) => {
    event.preventDefault();
    event.returnValue = '';
});

But there is a popup (I can't use package and library)但是有一个弹出窗口(我不能使用 package 和库)

And it is only the Delete API call that causes this refresh because from the console by calling delete(1), the page is refreshed并且只有 Delete API 调用会导致此刷新,因为通过调用 delete(1) 从控制台刷新页面

Any help would be greatly appriciated.任何帮助将不胜感激。

To fix the issue use: async/await .要解决此问题,请使用: async/await First,return the promise from the fetch request and then use await to wait for the request to complete before calling the event.preventDefault()首先,从获取请求中返回 promise,然后使用await等待请求完成,然后再调用event.preventDefault()

Issue is in you code is: the fetch request is async, so before completes the request page is refreshed您的代码中的问题是:获取请求是异步的,因此在完成请求页面之前会刷新

 async function deleteProduct(param) {
      event.preventDefault();
      const response = await fetch(`${api_Url}/products${param}`, {
        method: 'DELETE',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `bearer ${token}`
        },
      });
      console.log(response);
    }

click event listner is like this点击事件监听器是这样的

element.addEventListener('click', async (event) => {
    const Id = event.currentTarget.id;
    await deleteProduct(Id);
});

Try this尝试这个

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM