简体   繁体   English

api 调用会重新加载并刷新整个页面,而不仅仅是更新 div

[英]api call reloads and refreshes the entire page instead of just updating the div

I have this code here.我这里有这段代码。

          <div class="page" id="content-apiservicedemo">
            <div class="container">
            <hr>
            <p>here comes the simple api button</p>
            <button id="btn-call-api" disabled="true" onclick="callApi()">Call Api</button>
  
            <!-- Add a container to hold the response from the call -->
            <pre id="api-call-result"></pre> 
            </div>

I have this on the JS side of things.我在 JS 方面有这个。

    //this is calling the api 

    const callApi = async () => {

  try {

    // Get the access token from the Auth0 client
    const token = await auth0.getTokenSilently();

    // Make the call to the API, setting the token
    // in the Authorization header
    const hostURL1 = "https://localhost:44375/";
    const hostURL2 = "https://testserverxyz.azurewebsites.net/";

    const withoutauthURLendpoint = "WeatherForecast";
    const authURLendpoint = "api/TestWithoutDB/getvalue2";
    const response = await fetch(hostURL2 + authURLendpoint, {
      headers: {
        Authorization: `Bearer ${token}`
      }
    });

    // Fetch the JSON result
    const responseData = await response.json();

    // Display the result in the output element
    const responseElement = document.getElementById("api-call-result");

    responseElement.innerText = JSON.stringify(responseData, {}, 2);

    } catch (e) {
        // Display errors in the console
        console.error(e);
      }
    };

This is a single page JS application running on node JS.这是在节点 JS 上运行的单页 JS 应用程序。 For some reason, every time I use this button, the entire page is refreshing despite there being no code that asks for the entire page to be refreshed.出于某种原因,每次我使用这个按钮时,整个页面都会刷新,尽管没有代码要求刷新整个页面。

Note 1 - Also, i have another version of this code, that runs just fine.注 1 - 另外,我有这个代码的另一个版本,运行得很好。 Only difference is that I am playing around with some CSS modifications but HTML and JS are identical.唯一的区别是我在玩一些 CSS 修改,但 HTML 和 JS 是相同的。

So, is there some CSS that I may have removed which prevented the page from reloading?那么,是否有一些我可能已经删除的 CSS 阻止了页面重新加载? I thought CSS was about appearance only.我以为 CSS 只是关于外观。

Note 2笔记2

Here is the network call of the above code.这是上面代码的网络调用。

OPTIONS /api/TestWithoutDB/getvalue2 undefined
Host: baribasicidentityapiserverjuly28th2020.azurewebsites.net
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:79.0) Gecko/20100101 Firefox/79.0
Accept: */*
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate, br
Access-Control-Request-Method: GET
Access-Control-Request-Headers: authorization
Referer: http://localhost:3000/apiservicedemo
Origin: http://localhost:3000
Connection: keep-alive

Based on the above call, I am coming to the conclusion that, by the time the network call actually takes place, the token has been wiped out, and the call is being rejected.基于上述调用,我得出的结论是,当网络调用实际发生时,令牌已被清除,调用被拒绝。 Now, the token wiping part is as per my design, so that is not the problem.现在,令牌擦除部分是按照我的设计,所以这不是问题。 But, I am including that information to indicate that the reload happens before the code execution for the api call happens.但是,我包含该信息以表明重新加载发生在 api 调用的代码执行发生之前。

I have confirmed that when I do make the call, I am logged in and a token is definitely arriving into the call.我已经确认,当我拨打电话时,我已登录并且肯定会收到一个令牌。

Glad you were able to figure this out by removing the form tag.很高兴您能够通过删除表单标签来解决这个问题。

If you're interested in knowing more about why this is happening, it is related to the default action of your form being submitted by the button (happens with all forms, not just express js).如果您有兴趣进一步了解为什么会发生这种情况,这与按钮提交的表单的默认操作有关(所有 forms 都会发生,而不仅仅是 express js)。 It appears as if it's refreshing because you likely don't have an action attribute pointing at a script on the form, so it POSTs to itself/same page.它看起来好像很令人耳目一新,因为您可能没有指向表单上脚本的操作属性,因此它发布到自身/同一页面。

In the future, you could make use of the Event.preventDefault function to nullify the submission.将来,您可以使用Event.preventDefault function来取消提交。

Okay, so, I dont if anyone else will face a similar problem but I will post a solution here.好的,所以,如果其他人会遇到类似的问题,我不会,但我会在这里发布解决方案。

It was a good thing that I had a working sample to compare, line by line.我有一个工作样本可以逐行比较,这是一件好事。 The issue had to do with the container I was using.这个问题与我使用的容器有关。

My entire app was enclosed in a form tag.我的整个应用程序都包含在一个表单标签中。 (I had borrowed this code from a template that was also using many buttons but that was plain vanilla JS. This is also a plain vanilla JS but enclosed in a node JS Express front end app). (我从一个模板中借用了这段代码,该模板也使用了许多按钮,但那是普通的 JS。这也是一个普通的 JS,但包含在节点 JS Express 前端应用程序中)。

Looks like the way the express js app is setup, it takes any button being clicked and used to make an API call as a way to submit a form with entered values.看起来像 express js 应用程序的设置方式,它需要单击任何按钮并用于进行 API 调用,作为提交具有输入值的表单的一种方式。

So, I replaced the form tag with a div tag, and the issue is resolved.所以,我用 div 标签替换了 form 标签,问题就解决了。 the API is being called.正在调用 API。

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

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