Http 在react native中使用fetch polyfill作为键值对发送数据
以下代码用于使用fetch polyfill发出HTTP POST请求:Http 在react native中使用fetch polyfill作为键值对发送数据,http,react-native,fetch-api,Http,React Native,Fetch Api,以下代码用于使用fetch polyfill发出HTTP POST请求: fetch(url, { method: 'post', body: JSON.stringify({ 'token': this.state.token }) }) .then((response) => response.json()) .then((responseData) => { console.log(responseData) }) .done();
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)那样以键值对的形式发送数据。当然。查看github中的获取文档: 它使用document/domweb,但对于react原生案例应该是相同的-只需使用FormData对象并附加所有要发送的表单字段
var form = document.querySelector('form')
fetch('/users', {
method: 'post',
body: new FormData(form)
})
以及:
当然。查看github中的获取文档: 它使用document/domweb,但对于react原生案例应该是相同的-只需使用FormData对象并附加所有要发送的表单字段
var form = document.querySelector('form')
fetch('/users', {
method: 'post',
body: new FormData(form)
})
以及:
听起来您想要与querystring相同的格式,因此导入/需要一个类似的包,它似乎不依赖于任何浏览器功能,并且具有stringify方法:
queryString.stringify({
foo: 'bar',
nested: JSON.stringify({
unicorn: 'cake'
})
});
//=> foo=bar&nested=%7B%22unicorn%22%3A%22cake%22%7D
或者,您也可以只使用其源代码的相关部分,尽管这仍将受到以下限制:
然后,您可以在fetch
中的正文
参数中使用返回值:
fetch(url, {
method: 'post',
body: toQueryString({ 'token': this.state.token })
})
听起来您想要与querystring相同的格式,因此导入/需要一个类似的包,它似乎不依赖于任何浏览器功能,并且具有stringify方法:
queryString.stringify({
foo: 'bar',
nested: JSON.stringify({
unicorn: 'cake'
})
});
//=> foo=bar&nested=%7B%22unicorn%22%3A%22cake%22%7D
或者,您也可以只使用其源代码的相关部分,尽管这仍将受到以下限制:
然后,您可以在fetch
中的正文
参数中使用返回值:
fetch(url, {
method: 'post',
body: toQueryString({ 'token': this.state.token })
})
toQueryString是一种更清洁的解决方案。我发现我可以给body属性分配一个字符串,比如“key1=value1&key2=value2”,这样也可以。谢谢-我会接受你的回答。toQueryString是一个更干净的解决方案。我发现我可以给body属性分配一个字符串,比如“key1=value1&key2=value2”,这样也可以。谢谢-我会接受你的回答。