【发布时间】:2019-01-02 21:36:47
【问题描述】:
我有以下代码用于创建带有图像和一些正文参数的事件。当我没有图像时它工作正常,我使用react-native-image-crop-picker 来选择图像。从 react-native 发布数据时出现“网络请求失败”错误。该请求永远不会到达我的后端,因为我在那里没有日志。它与邮递员合作得很好。
我的代码:
const { name, date, description, location, uri, mime, time } = this.state;
const formData = new FormData();
formData.append('name', name)
formData.append('date', date)
formData.append('description', description)
formData.append('location', location)
formData.append('time', time)
formData.append('image',{
uri:uri,
mime:'image/jpeg',
name:`image${moment()}`
})
alert(JSON.stringify(formData));
const config = {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'multipart/form-data',
},
body: formData,
};
fetch(`http://${Config.apihost}:${Config.port}/events`,config).then((res) => res.json())
.then((res) => {
this.setState({ modalVisible: false, name:'', date: moment().format('YYYY-MM-DD'), description:'', Location: 'AlHedaya Masjid' })
this.props.addEvent(res.message);
// this.props.navigation.goBack();
}).catch((err) => alert(err));
我有另一个屏幕,其中包含不同数量的图片,例如画廊
const data = new FormData();
data.append('name', 'avatar');
images.map((res, i) => {
data.append('fileData[]', {
uri: res.path,
type: res.mime,
name: `image${i}${moment()}`
});
})
const config = {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'multipart/form-data',
},
body: data,
};
fetch(`http://${Config.apihost}:${Config.port}/events/${this.state.item.id}/photos`, config)
.then((checkStatusAndGetJSONResponse) => checkStatusAndGetJSONResponse.json())
.then((response) => {
if (response.status && response.message.length > 0) {
var images = this.state.images;
response.message.map(file => {
images.push(`http:${Config.apihost}:${Config.port}/images/${file.id}`);
});
this.setState({ images });
}
}).catch((err) => { alert(err) });
我看不出这两个代码之间的区别,但上面的代码给了我错误。
- 我正在安卓上测试
- 我使用的是 IP 地址而不是 localhost(我的其他请求正在工作,所以这不符合)
- 此链接中的解决方案均无效 React Native fetch() Network Request Failed
我错过了什么吗?
【问题讨论】:
-
应该
images.push("http:${Config.apihost}:${Config.port}/images/${file.id}");是images.push("http://${Config.apihost}:${Config.port}/images/${file.id}");吗? -
那是我真正成功发布到我的服务器的时候.. 我什至没有到达我的服务器,请求被卡在中间的某个地方。
-
不错的选择顺便说一句,但下面的代码工作正常......现在我更加困惑它为什么工作。
-
是的 - 只是在我查看您的代码时发表评论,因为稍后可能会出现问题
-
你是用安卓模拟器还是真机测试?
标签: javascript reactjs react-native fetch