【发布时间】:2020-06-18 13:22:33
【问题描述】:
我正在尝试从 react native 捕获图像并将其上传到服务器,但是当我发出 http 请求时出现以下错误:
[TypeError:网络请求失败]
这是我的代码,我已经按照本教程进行操作:
https://heartbeat.fritz.ai/how-to-upload-images-in-a-react-native-app-4cca03ded855
import React from 'react';
import {View, Image, Button} from 'react-native';
import ImagePicker from 'react-native-image-picker';
export default class App extends React.Component {
state = {
photo: null,
};
createFormData = (photo) => {
const data = new FormData();
data.append('photo', {
name: photo.fileName,
type: photo.type,
uri:
Platform.OS === 'android'
? photo.uri
: photo.uri.replace('file://', ''),
});
data.append('id', 1);
return data;
};
handleChoosePhoto = () => {
const options = {
noData: true,
};
ImagePicker.launchImageLibrary(options, (response) => {
if (response.uri) {
this.setState({photo: response});
}
});
};
handleUploadPhoto = () => {
fetch('http://192.168.1.104:3000/', {
method: 'POST',
body: this.createFormData(this.state.photo),
})
.then((response) => response.text())
.then((response) => {
console.log('upload success', response);
})
.catch((error) => {
console.log('upload error', error);
});
};
render() {
const {photo} = this.state;
return (
<View style={{flex: 1, alignItems: 'center', justifyContent: 'center'}}>
{photo && (
<React.Fragment>
<Image
source={{uri: photo.uri}}
style={{width: 300, height: 300}}
/>
<Button title="Upload" onPress={this.handleUploadPhoto} />
</React.Fragment>
)}
<Button title="Choose Photo" onPress={this.handleChoosePhoto} />
</View>
);
}
}
我试过了:
- 将“Content: multipart/form-data”添加到 http 请求标头
- 将 Accept: Accept: application/json" 添加到 http 请求标头
我注意到请求失败,只有当我将照片对象添加到“FormData”时,即当我删除以下代码时http请求才能正常运行:
data.append('photo', {
name: photo.fileName,
type: photo.type,
uri:
Platform.OS === 'android'
? photo.uri
: photo.uri.replace('file://', ''),
});
编辑 02-07-2020
我终于在这里找到了解决方案:
https://github.com/facebook/react-native/issues/28551#issuecomment-610652110
【问题讨论】:
-
我正在使用以下包 "react": "16.11.0", "react-native": "0.62.2", "react-native-image-picker": "^2.3 .1" 我正在开发的手机是小米红米 Note 5
-
你试过添加'file://' + photo.path 作为安卓的uri吗?
-
由于“网络请求失败”错误而到达这里的人可能有兴趣阅读this
标签: javascript node.js react-native fetch