我有一个简单的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,但由于某些原因,仍然会发生错误。
类似的问题并不完全相同:fetch response on client with form-data from server,Constructing multipart response
答复有两个问题
\r\n
而不是\n
。对于作为多部分边界的标头和正文中的MIME标头,都是如此。虽然浏览器似乎接受\n
作为标头(即使这不符合标准),但它对多部分MIME正文的宽容程度较低李>boundary \r\n
,而不是boundary
,即行结尾是必需的李>这解决了以下问题:
相关问题 更多 >
编程相关推荐