Get HTTP Body of Form in JavaScript

后端 未结 2 792
北海茫月
北海茫月 2020-12-04 01:09

Is it possible in Javascript to get the contents of the HTTP Body of the resulting HTTP request that would be sent when a Form is submitted?

Say I have a Form of typ

相关标签:
2条回答
  • 2020-12-04 01:18

    You can use Response, Response.body.getReader() which is a ReadableStream to read the contents of FormData object. Use TextDecoder to convert Uint8Array to readable text. Note, you cannot read stream and headers from the same Response object. Though you can create a new Response object from same input data and the read Headers

    var form = document.querySelector("form");
    form.onsubmit = (e) => {
      e.preventDefault();
      var formData = new FormData();
      var input = e.target.querySelector("input");
      formData.append("file", input.files[0], input.files[0].name);
    
      var response = new Response(formData);
      var stream = response.body;
      var reader = stream.getReader();
      var decoder = new TextDecoder();
      reader.read()
        .then(function processData(result) {
          if (result.done) {
            console.log("stream done");
            return;
          }
          var data = decoder.decode(result.value);
          console.log(data);
    
          return reader.read().then(processData);
        })
        .catch(function(err) {
          console.log("catch stream cancellation:", err);
        });
    
      reader.closed.then(function() {
        console.log("stream closed");
      });
    }
    <form method="POST" enctype="multipart/form-data">
      <input name="file" type="file" />
      <input type="submit">
    </form>

    0 讨论(0)
  • 2020-12-04 01:20

    No. There are no APIs that expose that information.

    You can attempt to manually construct the request, but there's no way to get the browser to prepare it for you.

    0 讨论(0)
提交回复
热议问题