ajax上传文件后,页面为什么会刷新?

使用ajax向后端发送文件,为什么上传成功后,页面会刷新呢?
先看下效果:

img

前端代码:

html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Documenttitle>
  
head>
<body>
  <input type="file" id="upload">
  <input class="upload-btn" type="button" value="点击上传" />
  <script>
    window.onload = function () {
      alert('页面刷新了');
    }
    const btn = document.querySelector('.upload-btn');
    btn.addEventListener('click', function (e) {
      let xhr;
      if (window.XMLHttpRequest) {
        xhr = new XMLHttpRequest();
      } else {
        // 兼容IE
        xhr = ActiveXObject('Microsoft.XMLHTTP');
      }
      let fd = new FormData();
      const file = document.querySelector('#upload');
      console.log(file.files);
      fd.append('file', file.files[0]);
      // 初始化
      console.log('UNSEDN', xhr.readyState);
      // 打开连接
      xhr.open('post', 'http://localhost:3001/upload');
      // xhr.setRequestHeader('Content-Type', 'multipart/form-data');
      xhr.send(fd);
      xhr.onreadystatechange = function () {
        if(this.readyState === 2){
       // 接收到响应头
        console.log("HEADERS_RECEIVED",xhr.readyState);
        }else if(this.readyState === 3){
            // 响应体加载中
          console.log("LOADING",xhr.readyState);
        }else if(this.readyState === 4){
            // 加载完成
            alert('加载完成了');
            console.log("DONE",xhr.readyState);
        }
      }
      // return false;
    });
  script>
body>
html>

后端代码:

const http = require('http');
const querystring = require("querystring");
const fs = require('fs');
const server = http.createServer((req, res) => {
  res.setHeader('Access-Control-Allow-Origin', '*');
  if (req.url === '/') {
    req.on('data', (data) => {
      console.log(data.toString());
    })
    req.on('end', () => {
      res.end('124');
    })
  }
  if (req.url === '/upload') {
    if (req.method.toLowerCase() === 'get') {
      // 返回一个用于文件上传的form
      res.writeHead(200, { 'Content-Type': 'text/html' });
      res.end(
        `
        
method="POST"> <input type="file" name="upload" multiple="multiple" /> <input type="submit" value="Upload" />
` ) } else if (req.method.toLowerCase() === 'post') { if (req.headers['content-type'].indexOf('multipart/form-data') !== -1) { parseFormData(req, res); } else { res.end('你好') } } } }); function parseFormData (req, res) { req.setEncoding('binary'); let body = ''; // 文件数据 let fileName = ''; // 文件名 // 边界字符串 const boundary = req.headers['content-type'] .split('; ')[1] .replace('boundary=', ''); req.on('data', function (chunk) { body += chunk; }); req.on("end", function() { const file = querystring.parse(body, "\r\n", ":"); const fileInfo = file["Content-Disposition"].split(";"); for (value in fileInfo) { if (fileInfo[value].indexOf("filename=") !== -1) { fileName = fileInfo[value].substring(11, fileInfo[value].length - 1); // 这是处理什么情况的? if (fileName.indexOf("\\") != -1) { fileName = fileName.substring(fileName.lastIndexOf("\\") + 1); } break } } const entireData = body.toString(); contentType = file["Content-Type"].substring(1); //获取文件二进制数据开始位置,即contentType的结尾 const upperBoundary = entireData.indexOf(contentType) + contentType.length; const shorterData = entireData.substring(upperBoundary); // 替换开始位置的空格 const binaryDataAlmost = shorterData .replace(/^\s\s*/, "") .replace(/\s\s*$/, ""); // 去除数据末尾的额外数据,即: "--"+ boundary + "--" const binaryData = binaryDataAlmost.substring(0, binaryDataAlmost.indexOf("--" + boundary + "--")); const bufferData = new Buffer.from(binaryData, "binary"); fs.writeFile(fileName, bufferData, function(err) { if (err) { console.log(err); } res.end("sucess"); }); }); } server.listen(3001);

看到你这里是动态添加了个form标签的,原生form表单提交的话就会有这个问题,可以看下这个链接,或者根据这个链接的标题搜索更多答案
https://blog.csdn.net/weixin_47896488/article/details/122511889