2016-02-04 39 views
24

我取這樣一個URL抓取後:與多形式的數據

fetch(url, { 
    mode: 'no-cors', 
    method: method || null, 
    headers: { 
    'Accept': 'application/json, application/xml, text/plain, text/html, *.*', 
    'Content-Type': 'multipart/form-data' 
    }, 
    body: JSON.stringify(data) || null, 
}).then(function(response) { 
    console.log(response.status) 
    console.log("response"); 
    console.log(response) 
}) 

我的API預計該數據是multipart/form-data所以我使用這種類型的content-type ...但它給我一個迴應狀態代碼400.

我的代碼有什麼問題?

回答

44

你設置Content-Typemultipart/form-data,但是如果使用對身體的數據,它返回application/jsonJSON.stringify。您的內容類型不匹配。

您需要將數據編碼爲multipart/form-data而不是json。上傳文件時通常使用multipart/form-data,並且比application/x-www-form-urlencoded(這是HTML表單的默認值)複雜一點。

multipart/form-data的規格可在RFC 1867中找到。

有關如何通過javascript提交該類數據的指導,請參見here

的基本思想是用FormData對象(在IE < 10不支持):

function sendData(url, data) { 
    var formData = new FormData(); 

    for(var name in data) { 
    formData.append(name, data[name]); 
    } 

    fetch(url, { 
    method: 'POST', 
    body: formData 
    }).then(function (response) { 
    ... 
    }); 
} 
7

我最近與IPFS工作,並制定了這一點。對於IPFS上傳文件的捲曲例子是這樣的:

curl -i -H "Content-Type: multipart/form-data; boundary=CUSTOM" -d $'--CUSTOM\r\nContent-Type: multipart/octet-stream\r\nContent-Disposition: file; filename="test"\r\n\r\nHello World!\n--CUSTOM--' "http://localhost:5001/api/v0/add" 

的基本思想是,每個部分(由字符串boundary--拆分)有它自己的頭(在第二部分Content-Type,例如。 )FormData對象爲您管理所有這些,所以它是實現我們目標的更好方法。

這意味着這樣獲取API:

const formData = new FormData() 
formData.append('blob', new Blob(['Hello World!\n']), 'test') 

fetch('http://localhost:5001/api/v0/add', { 
    method: 'POST', 
    body: formData 
}) 
.then(r => r.json()) 
.then(data => { 
    console.log(data) 
})