编程语言
首页 > 编程语言> > javascript-在XHR中将multipart / form-data用作Content-Type时得到“ 400 Bad Request”

javascript-在XHR中将multipart / form-data用作Content-Type时得到“ 400 Bad Request”

作者:互联网

我有一个发送一些数据的AJAX请求.数据符合multipart / form-data specification.

我面临的问题是浏览器将Content-Type标头设置为text / plain,它应该是multipart / form-data.

我尝试这样做:request.setRequestHeader(“ Content-Type”,“ multipart / form-data”);但这会产生400错误的请求错误.

如果我这样做request.setRequestHeader(“ Content-Typexxxx”,“ multipart / form-data”);没有错误,已设置“ Content-Typexxxx”标头,但显然对我没有帮助.

我猜这里有一个可以设置的有效Content-Type标头列表,而“ multipart / form-data”不在其中,但是我找不到解决方案.

实际发送的数据样本:

Content-Type: multipart/form-data; boundary=l3iPy71otz

--l3iPy71otz
Content-Disposition: form-data; name="titluPublic"

Variation_1
--l3iPy71otz
Content-Disposition: form-data; name="nr_versiune"


--l3iPy71otz--

谢谢!

解决方法:

您没有在请求标头中设置边界,如下所示:

request.setRequestHeader("Content-Type", "multipart/form-data; boundary=l3iPy71otz");

有关更多信息,请参见RFC 2045

5 Content-Type Header Field
[…]
Parameters are modifiers of the media
subtype, and as such do not
fundamentally affect the nature of the
content. The set of meaningful
parameters depends on the media type
and subtype. Most parameters are
associated with a single specific
subtype. However, a given
top-level media type may define
parameters which are applicable to
any subtype of that type. Parameters
may be required by their defining
content type or subtype or they may be
optional. MIME implementations must
ignore any parameters whose names they
do not recognize.

For example, the “charset”
parameter is applicable to any subtype
of “text”, while the “boundary”
parameter is required for any subtype
of the “multipart” media type.

更新:当将字符集添加到请求标头中的Content-type而不是正文的消息边界中时,我发现了另一个问题on the net,这也适用于您的测试用例.这似乎不是一个可行的解决方案,但也许会有所帮助.

在您的情况下,在请求标头和消息边界中显式添加一个字符集:

data.params += "--" + data.uniqid + "; charset=UTF-8" + data.crlf;
…
request.setRequestHeader("Content-Type", "multipart/form-data; boundary=" + data.uniqid + "; charset=UTF-8");

更新2:在本地尝试此操作后,我注意到引导边界并没有被这样识别,而是被解释为最后一个参数内容(在我的宽容服务器上).也许这是导致Apache抛出400 Bad Request错误的原因.

经过一番尝试和错误之后,我注意到这是由于服务器期望字符集位于每个边界(甚至是最后一个边界)中引起的.为避免混淆,我决定在请求标头中将边界集之前的字符集显式设置为边界,这样边界将成为Content-type请求标头中的最后一个参数.此后,一切似乎都正常.

data.params = "Content-Type: multipart/form-data; boundary=" + data.uniqid;
…
data.params += "--" + data.uniqid + data.crlf;
…
data.params += "--" + data.uniqid + "--";
…
request.setRequestHeader("Content-Type", "multipart/form-data; charset=UTF-8; boundary=" + data.uniqid);

标签:ajax,http-headers,header,xmlhttprequest,javascript
来源: https://codeday.me/bug/20191105/1995501.html