Javascript 试图理解多部分响应错误“;TypeError:无法将内容解析为FormData;

Javascript 试图理解多部分响应错误“;TypeError:无法将内容解析为FormData;,javascript,python,sockets,http,multipart,Javascript,Python,Sockets,Http,Multipart,我有一个简单的python服务器,它正在向javascript客户端发送一个多部分响应,但我遇到了这样一个错误TypeError:无法将内容解析为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 = so

我有一个简单的python服务器,它正在向javascript客户端发送一个多部分响应,但我遇到了这样一个错误
TypeError:无法将内容解析为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,但由于某些原因,仍然会发生错误。


类似的问题并不完全相同:,

回答有两个问题

  • 行尾应该是
    \r\n
    而不是
    \n
    。对于作为多部分边界的标头和正文中的MIME标头,都是如此。虽然浏览器似乎接受头的
    \n
    (即使这不符合标准),但对多部分MIME正文的宽容程度较低
  • 多部分MIME正文的结尾是
    --boundary-->\r\n
    ,而不是
    --boundary
    ,即行结尾是必需的
这解决了以下问题:

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

我马上去看看!这就成功了,谢谢你抓住了我的非标准问题!