假设有一个PUT
请求,请求体类型为[object formData]
:
let fd = new FormData();
let i = document.querySelector('input[type="file"]');
fd.append('name', 'abc123');
fd.append('avatar', i.files[0]);
fetch('https://example.com/profile/avatar', {
method: 'PUT',
body: fd
})
.then(r => r.json())
.then(d => {
console.log('Success:', d);
})
.catch(e => {
console.error('Error:', e);
});
直接这样发出请求,是没问题的,但是如果定义Content-Type
:
fetch('https://example.com/profile/avatar', {
method: 'PUT',
headers: {
'Content-Type': 'multipart/form-data',
},
body: fd,
})
报缺少multipart boundary
的错误:
no multipart boundary param in Content-Type
尝试补齐boundary
:
fetch('https://example.com/profile/avatar', {
method: 'PUT',
headers: {
'Content-Type': 'multipart/form-data; boundary=----WebKitFormBoundaryguyoFrGTqdPGKQUy',
},
body: fd,
})
报EOF
错误:
multipart: NextPart: EOF
搜了下相关问题,都在讲body
的类型为[object formData]
时浏览器会自动将Content-Type
设置为multipart/form-data
并自动补齐boundary
,不需要自定义。
很好奇,为什么自定义会出错?
以及浏览器是基于什么逻辑来生boundary
的?