Trying to understand the multipart response error "TypeError: Could not parse content as FormData."

Trying to understand the multipart response error "TypeError: Could not parse content as FormData."

我有一个简单的 python 服务器正在向 javascript 客户端发送多部分响应,但我收到此错误 TypeError: Could not parse content as FormData.

python 服务器

import time
import socket
import socketserver
import ssl
import numpy as np
from io import BytesIO
from PIL import Image

transfer_bytes = BytesIO()


s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
## the reusaddr part means you don't have to wait to restart
s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)

s.bind(("localhost",58886))
s.listen(1)
def handle_request(conn):
    print("handling!!")
    response_header = f"""
HTTP/1.1 200 OK
Access-Control-Allow-Origin: *
Content-Type:multipart/form-data;boundary=xxx  

--xxx
Content-Type: text/plain ;
Content-Disposition: form-data; name="first"

hello world
--xxx
Content-Type: text/plain ;
Content-Disposition: form-data; name="second"

end
--xxx--
    """.strip()
    ## prepare the multipart response

    conn.send(f"{response_header}".encode())
    

while True:
    print("waiting for next request")
    conn,addr = s.accept()
    #conn, addr = ssock.accept()
    handle_request(conn)
    conn.shutdown(socket.SHUT_RDWR)
    conn.close()
    print("fulfilled request")
    time.sleep(1)

javascript 客户

window.onload = async ()=> {
  fetch("http://localhost:58886").then(res=>res.formData()).then(t=> console.log(t)).catch(err => console.log(err))
}

在 firefox 的网络控制台中,我看到客户端将类型识别为 multipart,但由于某种原因,错误仍然发生。

不完全相同的相似问题:, Constructing multipart response

响应有两个问题

  • 行尾应该是 \r\n 而不是 \n。对于作为多部分边界的 header 和 body 中的 MIME header 都是如此。虽然浏览器似乎接受 \n 作为 header(即使这不符合标准),但它对多部分 MIME body.
  • 的宽容度较低
  • 多部分 MIME body 的结尾是 --boundary--\r\n,而不是 --boundary,即行结尾是必不可少的。

这解决了这些问题:

response_header = str.replace(response_header, "\n", "\r\n") + "\r\n"