简体   繁体   English

js fetch 请求重新加载页面两次

[英]Js fetch request reloads the page twice

I make a POST fetch request with formdata as body, but it reloads the page twice, once when it sends the data and once when it gets back.(it sends to a flask server that sends back a pdf)我使用 formdata 作为正文发出 POST 获取请求,但它会重新加载页面两次,一次是在发送数据时,一次是在数据返回时。(它发送到 flask 服务器,该服务器发回 pdf)

Html: Html:

<body>
    <input type="file" id="fileInput" accept=".mxl, .mscz" name="file"/>
    <button class="upload" id="upload">Upload</button>
</body>

Js:杰斯:

function uploadFile(file) {
    fetch('http://127.0.0.1:5000/upload', {
    method: 'POST',
    body: file,
    })
    .then(response => {
       // downloadResponseAsFile(response);
  })
}

function downloadResponseAsFile(response) {
}

const uploadButton = document.querySelector('.upload');
uploadButton.addEventListener('click',(e)  {
  e.preventDefault();
  const fileInput = document.querySelector('#fileInput');     
  const file = fileInput.files[0];
  
  const formData = new FormData();
  formData.append('file', file);

  uploadFile(formData);
});

When i don't use the formdata or just don't choose the file it works(doesn't reload the page).当我不使用表单数据或只是不选择它工作的文件时(不重新加载页面)。 If i dont use event listener, just onclick function it is still the same.如果我不使用事件监听器,只是 onclick function 它仍然是一样的。 What is the cause of this?这是什么原因?

EDIT: It looks like the live server is the one who refreshes the page when I open the file and try to send it.编辑:看起来实时服务器是在我打开文件并尝试发送文件时刷新页面的服务器。

You can wrap your input element with a <form> element and before you submit call the event.preventDefault() on the form element.您可以使用<form>元素包装您的输入元素,并在提交之前调用表单元素上的event.preventDefault() This will prevent the reloading of your page这将阻止重新加载您的页面

I found it, when I sent the file to the server it was in the same folder as the webpage(stupid thing) and the live server(which hosted the webpage) thought that i changed a file so it refreshed the page.我找到了,当我将文件发送到服务器时,它与网页位于同一文件夹中(愚蠢的东西),实时服务器(托管网页)认为我更改了文件,因此它刷新了页面。 Now I moved the server and webpage to different folders and it works.现在我将服务器和网页移动到不同的文件夹并且它可以工作。

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

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