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

2024-03-29 10:38:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个简单的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,但由于某些原因,仍然会发生错误。 enter image description hereenter image description here

类似的问题并不完全相同:fetch response on client with form-data from serverConstructing multipart response


Tags: fromimportform服务器客户端dataresponserequest
1条回答
网友
1楼 · 发布于 2024-03-29 10:38:40

答复有两个问题

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

这解决了以下问题:

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

相关问题 更多 >