React native 如何使用RNFetchBlob或任何其他方式在react native中发布多部分
我正在尝试以react native发送多部分请求。我尝试了很多方法,但都不管用。请检查这个例子React native 如何使用RNFetchBlob或任何其他方式在react native中发布多部分,react-native,blob,fetch,multipart,React Native,Blob,Fetch,Multipart,我正在尝试以react native发送多部分请求。我尝试了很多方法,但都不管用。请检查这个例子 const data ={ "person": this.state.person, "email": this.state.email, "password":this.state.password, "confirmPassword":this.state.confirmPassword, "otp": {
const data ={
"person": this.state.person,
"email": this.state.email,
"password":this.state.password,
"confirmPassword":this.state.confirmPassword,
"otp": {
"secret":this.state.otp
},
}
RNFetchBlob.fetch('POST', '${server}api/user-registration/register', {
'Content-Type' : 'multipart/form-data',
}, [
{
name:"data",data:JSON.stringify(data)
}
]).then((resp) => {
console.log(resp)
}).catch((err) => {
console.log(err)
})
我得到了415的答复。看起来它没有将多部分/表单数据放在标题中
我已经用Reactjs试过了,它完全有效。
这是Reactjs中的一个示例
const eventData = new FormData();
eventData.append('data', new Blob([JSON.stringify(data)], { type: "application/json" }));
axios.post('${server}api/user-registration/register',eventData,{headers:{}})
有人能看到RNFetchBlob代码有什么问题吗
像这样使用普通文本
使用类似此代码的文件
然后通常使用此方法或您自己的方法调用API
您可以使用名为
axios
的库
let formData = new FormData();
formData.set("field1", field1_value);
并使用axios发出Post请求:
axios({
method: "POST",
url: "<put-your-url-here>",
data: formData,
config: {
headers: {
'Content-Type': "multipart/form-data"
}
}
}).then(response=>handler).catch(error=>errorHandler);
axios({
方法:“张贴”,
url:“”,
数据:formData,
配置:{
标题:{
“内容类型”:“多部分/表单数据”
}
}
}).then(response=>handler).catch(error=>errorHandler);
在这里,
handler
是一个将响应作为输入并对其进行处理的函数,errorHandler
是一个接收错误并对其进行处理的函数。虽然这段代码可以解决问题,但如何解决问题以及为什么解决问题会真正有助于提高帖子的质量,而且可能会得到更多的支持票。请记住,你是在将来回答读者的问题,而不仅仅是现在提问的人。请编辑您的答案,添加解释,并说明适用的限制和假设。
RNFetchBlob.fetch('POST', 'your serviceUrl', {
Authorization: "Bearer "+token,
'Content-Type': 'multipart/form-data',
}, [
{ name: 'file', filename: 'image.png', type: 'image/png', data: JSON.stringify(RNFetchBlob.wrap(Imageuri))}])then((resp) => {
//response body
}).catch((err) => {
console.log('error---------', err)
// ...
})
let formData = new FormData();
formData.set("field1", field1_value);
axios({
method: "POST",
url: "<put-your-url-here>",
data: formData,
config: {
headers: {
'Content-Type': "multipart/form-data"
}
}
}).then(response=>handler).catch(error=>errorHandler);
RNFetchBlob.fetch('POST', 'your serviceUrl', {
Authorization: "Bearer "+token,
'Content-Type': 'multipart/form-data',
}, [
{ name: 'file', filename: 'image.png', type: 'image/png', data: JSON.stringify(RNFetchBlob.wrap(Imageuri))}])then((resp) => {
//response body
}).catch((err) => {
console.log('error---------', err)
// ...
})