2015-07-03 45 views
1

下面的代碼是使HTTP POST請求與取填充工具填充工具發送數據作爲鍵 - 值對:使用取在反應天然

fetch(url, { 
    method: 'post', 
    body: JSON.stringify({ 
    'token': this.state.token 
    }) 
}) 
    .then((response) => response.json()) 
    .then((responseData) => { 
    console.log(responseData) 
    }) 
    .done(); 

該請求發送的數據作爲一個字符串化JSON OBJ。有沒有辦法將數據作爲鍵值對發送,類似於python中的requests.post(url,data = payload)。

回答

7

聽起來像是你想要的格式相同查詢字符串,所以進口/需要一個包狀https://www.npmjs.com/package/query-string這似乎不依賴於任何瀏覽器的功能,並有一個字符串化方法:

queryString.stringify({ 
    foo: 'bar', 
    nested: JSON.stringify({ 
     unicorn: 'cake' 
    }) 
}); 

//=> foo=bar&nested=%7B%22unicorn%22%3A%22cake%22%7D 

或者你可以只使用它的源代碼的相關部分,儘管這仍然會受到its license

function toQueryString(obj) { 
    return obj ? Object.keys(obj).sort().map(function (key) { 
     var val = obj[key]; 

     if (Array.isArray(val)) { 
      return val.sort().map(function (val2) { 
       return encodeURIComponent(key) + '=' + encodeURIComponent(val2); 
      }).join('&'); 
     } 

     return encodeURIComponent(key) + '=' + encodeURIComponent(val); 
    }).join('&') : ''; 
} 

然後,您可以使用返回值在body參數fetch

fetch(url, { 
    method: 'post', 
    body: toQueryString({ 'token': this.state.token }) 
}) 
+0

toQueryString是一個清晰的解決方案。我發現我可以將一個像「key1 = value1&key2 = value2」這樣的字符串賦給body屬性,這也適用。謝謝 - 我會接受你的答案。 – jisu

+0

你,先生,是老闆!非常感謝 –

-1

當然。查看github中的獲取文檔:https://github.com/github/fetch

它使用document/DOM web,但它應該與react-native相同 - 只需使用FormData對象並附加所有要發送的表單字段即可。

var form = document.querySelector('form') 

fetch('/users', { 
    method: 'post', 
    body: new FormData(form) 
}) 

和:

var input = document.querySelector('input[type="file"]') 

var data = new FormData() 
data.append('file', input.files[0]) 
data.append('user', 'hubot') 

fetch('/avatars', { 
    method: 'post', 
    body: data 
}) 
相關問題