在 JavaScript 中获取表单的 HTTP 正文 [英] Get HTTP Body of Form in JavaScript

查看:29
本文介绍了在 JavaScript 中获取表单的 HTTP 正文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在 Javascript 中获取提交表单时将发送的结果 HTTP 请求的 HTTP 正文的内容?

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?

假设我有一个POST"类型的表单,其中包含一个文件输入和一些其他输入字段以及一个multipart/form-data"的 enctype 属性.我想获得浏览器将生成的请求的逐字 HTTP 正文和可能的 HTTP 标头如果我提交了表单(没有实际提交它).

Say I have a Form of type 'POST' with a file input and some other input fields and an enctype attribute of 'multipart/form-data'. I would like to get the verbatim HTTP Body and possibly HTTP Headers of the request the browser would generate if I submitted the form (without actually submitting it).

推荐答案

你可以使用 Response, Response.body.getReader() 这是一个 ReadableStream 读取FormData 对象的内容.使用 TextDecoderUint8Array 转换为可读文本.请注意,您不能从同一个 Response 对象读取流和标头.虽然您可以从相同的输入数据和读取的 Headers

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>

这篇关于在 JavaScript 中获取表单的 HTTP 正文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆